7. Entity Locking
Prev | Chapter 8. EntityManager | Next

## 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 `javax.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 for `OPTIMISTIC`.

- `WRITE`: A synonym for `OPTIMISTIC_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.

### 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.

Prev | Up | Next
6. Query Factory | Home | 8. Retrieving Properties Information