Pessimistic Locking in JPA 2 and Hibernate

Pessimistic Locking in Hibernate

With Hibernate the database obtains the locking and the framework never locks the objects in memory. The LockMode class provides the following set of locks, which can be obtained in a Hibernate application:

LockMode.WRITE: This lock is obtained when Hibernate updates or inserts a new row. LockMode.WRITE is an internal mode (default) and is not specified in the application because it is obtained automatically when a new row is inserted to the database by the framework.

LockMode.UPGRADE: This lock is obtained when a user makes an explicit request using SELECT .. FOR UPDATE. This lock is valid only on databases that support the SELECT .. FOR UPDATE SQL syntax.

LockMode.UPGRADE_NOWAIT: This lock is acquired when a user makes an explicit request using SELECT. . FOR UPDATE NOWAIT, which is supported only by Oracle.

LockMode.READ: This lock is obtained automatically when the framework reads the data under Repeatable Read or Serializable Isolation mode. A version check is performed to compare the version number of the object in memory to the record in the database. This lock can be acquired explicitly by invoking Hibernate APIs (more on this shortly).

LockMode.NONE: This represents the absence of a lock. At the end of each transaction objects attain this lock mode.

The user can acquire locks explicitly by invoking one of the following Hibernate API:

Session.load(): This method is invoked by specifying the locking mode as UPGRADE or UPDATE_NOWAIT . If the object is not loaded by session, then SELECT .. FOR UPDATE is executed to load the object. If the object is loaded with a less restrictive lock, then the framework invokes lock() for that object.

Session.lock(): This method performs a version number check when the lock mode is READ, UPGRADE or UPGRADE_NOWAIT. When the lock mode is UPGRADE or UPGRADE_NOWAIT, the SELECT .. FOR UPDATE statement is used.

Query.setLockMode(): This method is used to set the lock mode for the object specified in the FROM clause of the Query string.

Conclusion

JPA 2 and Hibernate both support pessimistic locking as a concurrency control mechanism, but not in the same way. In this article, we compared how the two technologies implement this feature.

Acknowledgements

The authors would like to sincerely thank Mr. Subrahmanya SV (VP, ECOM Research Group, E&R) for his ideas, guidance, support and constant encouragement and Ms. Mahalakshmi for kindly reviewing this article and providing valuable comments.

About the Authors

Sangeetha S. works as a Senior Technical Architect at the E-Commerce Research Labs at Infosys Technologies. She has over 10 years of experience in design and development of Java and Java EE applications. She has co-authored a book on 'J2EE Architecture' and also has written articles for online Java publications.