What is optimistic and pessimistic locking in Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, optimistic and pessimistic locking are mechanisms for managing concurrent access to data.
Optimistic locking assumes that conflicts during simultaneous data updates are rare. It does not lock records in the database but checks upon saving whether the data has changed since it was read. It is usually implemented through a version field (e.g., @Version). If the version has changed, an exception is thrown, and the transaction is rolled back.
Example of using optimistic locking:
@Entity
public class Product {
@Id
private Long id;
@Version
private int version;
private String name;
// getters/setters
}
Pessimistic locking assumes conflicts are likely and immediately locks the record in the database for the duration of the transaction, so other transactions cannot modify it. In Hibernate, this can be done using the lock() method with a lock mode, such as LockMode.PESSIMISTIC_WRITE.
Example of pessimistic locking:
Product product = session.get(Product.class, id, LockMode.PESSIMISTIC_WRITE);
// now the record is locked for other transactions
Optimistic locking is better suited for systems with low contention, while pessimistic locking is used when strict change sequencing and high contention are important.