11.5. Pessimistic Locking
11.5.1. About Pessimistic Locking Copy linkLink copied to clipboard!
Copy linkLink copied to clipboard!
It is not intended that users spend much time worrying about locking strategies. It is usually enough to specify an isolation level for the JDBC connections and then simply let the database do all the work. However, advanced users may wish to obtain exclusive pessimistic locks or re-obtain locks at the start of a new transaction.
Hibernate will always use the locking mechanism of the database; it never lock objects in memory.
The
LockMode class defines the different lock levels that can be acquired by Hibernate. A lock is obtained by the following mechanisms:
LockMode.WRITEis acquired automatically when Hibernate updates or inserts a row.LockMode.UPGRADEcan be acquired upon explicit user request usingSELECT ... FOR UPDATEon databases which support that syntax.LockMode.UPGRADE_NOWAITcan be acquired upon explicit user request using aSELECT ... FOR UPDATE NOWAITunder Oracle.LockMode.READis acquired automatically when Hibernate reads data under Repeatable Read or Serializable isolation level. It can be re-acquired by explicit user request.LockMode.NONErepresents the absence of a lock. All objects switch to this lock mode at the end of aTransaction. Objects associated with the session via a call toupdate()orsaveOrUpdate()also start out in this lock mode.
The "explicit user request" is expressed in one of the following ways:
- A call to
Session.load(), specifying aLockMode. - A call to
Session.lock(). - A call to
Query.setLockMode().
If
Session.load() is called with UPGRADE or UPGRADE_NOWAIT, and the requested object was not yet loaded by the session, the object is loaded using SELECT ... FOR UPDATE. If load() is called for an object that is already loaded with a less restrictive lock than the one requested, Hibernate calls lock() for that object.
Session.lock() performs a version number check if the specified lock mode is READ, UPGRADE or UPGRADE_NOWAIT. In the case of UPGRADE or UPGRADE_NOWAIT, SELECT ... FOR UPDATE is used.
If the requested lock mode is not supported by the database, Hibernate uses an appropriate alternate mode instead of throwing an exception. This ensures that applications are portable.