2.8.7. Entity Locking
In the area of concurrency control, the JPA specification supports optimistic and pessimistic locking.
public void lock(Object entity, LockModeType mode);
This method locks the given entity using the named mode. The jakarta.persistence.LockModeType enum defines eight modes:
-
OPTIMISTIC: Optimistic locking. -
OPTIMISTIC_FORCE_INCREMENT: Optimistic locking. When a transaction is committed, the entity’s version column will be incremented even if the entity’s state did not change in the transaction. -
PESSIMISTIC_READ: Pessimistic locking. Other transactions may concurrently read the entity, but cannot concurrently update it. -
PESSIMISTIC_WRITE: Pessimistic locking. Other transactions cannot concurrently read or write the entity. -
PESSIMISTIC_FORCE_INCREMENT: Pessimistic locking. Other transactions cannot concurrently read or write the entity. When a transaction is committed, the entity’s version column will be incremented even if the entity’s state did not change in the transaction. -
READ: A synonym forOPTIMISTIC. -
WRITE: A synonym forOPTIMISTIC_FORCE_INCREMENT. -
NONE: No locking is performed.
Entities can also be locked at the time when entity state gets loaded from the datastore.
This is achieved by supplying a lock mode to the respective versions of find and refresh methods.
If an entity state is to be loaded by a query, a lock mode can be passed to the Query.setLockMode and TypedQuery.setLockMode methods.
public LockModeType getLockMode(Object entity);
Returns the lock mode currently held by the given entity.
|
|
|