LockMode in EJB3 Persistence NamedQuery

1.5k Views Asked by At

How do we specify LockMode in EJB3 Persistence NamedQuery? I want to add Pessimistic LockMode to my existing select so that I can update if necessary but surprisingly Query object doesnot have setLockMode(xxx) method ( My understanding was if JPA, asubset of EJB3 persistence, exposes setLockMode, EJB3 persistence should have the method available too).

Query query = em.createNamedQuery("findOptoutStudent");
query.setParameter("optoutIndicator", optoutIndicator);
List<Student> students = query.getResultList();
return students.get(0);

I would assume I dont have to change the query manually to "select for update".

Thanks Kevin

1

There are 1 best solutions below

3
On

Pessimistic Lock Mode :

  • PESSIMISTIC_READ which represents a shared lock. Lock request fails when another entity manager has acquired PESSIMISTIC_WRITE.

  • PESSIMISTIC_WRITE which represents an exclusive lock. Lock request fails when another entity manager has acquired either of the locks on the object.

Applying lock on the object

entityManager.lock(object, LockModeType.PESSIMISTIC_READ)

Releasing the lock afterwards

entityManager.lock(object, LockModeType.NONE)