Locking is essential to avoid any update collision from two different users at the same time or dirty reading. JPA generally supports two types of locking: Optimistic locking and Pessimistic locking.
In this blog, we'll talk about Optimistic locking.
In Optimistic locking, an exception is thrown if the update is performed on an old object (if the value is different/changed in the database). ObjectDB enabled optimistic locking by default. It stores a version number in every entity that gets incremented by one on every change/ transaction. Hence, on every commit, it checks if the version is the same. If not, it throws OptimisticLockException.
Version attributes are created by using @version, an entity class.
@Entity public class Employee { @Id private Long id; private String name; private String designation; @Version private Integer version; }
An optimistic lock is enabled by default for the versioned entities; however, you can explicitly request an optimistic lock. There are several ways to do this:
1. Find method of entityManager
Pass a parameter LockModeType. OPTIMISTIC in find function.
entityManager.find(Employee.class, id, LockModeType.OPTIMISTIC)
2. setLockMode of query
you can use setLockMode function of Query to enable the lock.
Query query = entityManager.createQuery("from Employee where id = :id"); query.setParameter("id", id); query.setLockMode(LockModeType.OPTIMISTIC_INCREMENT); query.getResultList()
3. Refresh
Pass parameter of LockModeType in refresh, which a method of enitityManager.
Employee employee = entityManager.find(Employee.class, id); entityManager.refresh(Employee, LockModeType.READ);
4. Explicit Locking
Another method, lock of enitityManager is available to directly apply lock on a particular enitiy.
Employee employee = entityManager.find(Employee.class, id); entityManager.lock(employee, LockModeType.OPTIMISTIC);
5. NamedQuery
You can also use Named query.
@NamedQuery(name="optimisticLock", query="SELECT e FROM Employee e WHERE e.id LIKE :id", lockMode = WRITE)
Lock Modes:
JPA provides two types of optimistic lock modes:
1. OPTIMISTIC or READ : to obtain an optimistic lock for all entities containing version.
2. OPTIMISTIC_FORCE_INCREMENT or WRITE : to obtain optimistic lock similar to OPTIMISTIC along with the increment of version value.