Close

JPA - Explicitly setting a LockModeType

[Updated: Nov 15, 2018, Created: Dec 18, 2017]

In previous examples, we saw how optimistic locking is used implicitly. The application may also explicitly specify one of the lock modes defined in javax.persistence.LockModeType enum.

The enum LockModeType

Following is a snippet of LockModeType:

package javax.persistence;
...
public enum LockModeType {
    READ,//Synonymous with OPTIMISTIC.
    WRITE,//Synonymous with OPTIMISTIC_FORCE_INCREMENT.
    OPTIMISTIC,//Optimistic lock.
    OPTIMISTIC_FORCE_INCREMENT,//Optimistic lock, with version update.
    PESSIMISTIC_READ,//Pessimistic read lock.
    PESSIMISTIC_WRITE,//Pessimistic write lock.
    PESSIMISTIC_FORCE_INCREMENT,//Pessimistic write lock, with version update.
    NONE//No lock.
}

How to specify LockModeType?

Following public methods of the EntityManager can be used to specify one of the above modes:

void lock(Object entity, LockModeType lockMode)
void lock(Object entity, LockModeType lockMode, Map<String, Object> properties)
<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode)
<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties)
void refresh(Object entity, LockModeType lockMode)
void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties)

Other than above methods, Query API also has methods to specify the locks (which we will be covering in future tutorials).

In some of the next tutorial examples, we will understand use of EntityManager to specify a lock mode.

See Also