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:

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.

Note

  • OpenJPA differentiates between PESSIMISTIC_READ and PESSIMISTIC_WRITE lock modes only with DB2 databases. While running with other databases, there is no distinction between these two modes because PESSIMISTIC_READ lock mode is upgraded to PESSIMISTIC_WRITE.

  • OpenJPA has additional APIs for controlling entity locking. See Section 3, “ Object Locking ” in the Reference Guide for details.