0

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

phewataal
  • 1,107
  • 4
  • 12
  • 23

1 Answers1

0

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)
Nayan Wadekar
  • 11,444
  • 4
  • 50
  • 73
  • Can I apply a lock to the object retrieved by NamedQuery? Or does it have to be the object returned by em.find only? I have something like: Query query = em.createNamedQuery("findRecords"); query.setParameter("incomingInd", incomingInd); query.getResultList().get(0); – phewataal Dec 15 '11 at 17:06
  • Yes, you can apply lock mode to NamedQuery by an optional element - "lockMode" in its definition. – Nayan Wadekar Dec 17 '11 at 15:33
  • The version required for this is JPA 2.0, – Nayan Wadekar Dec 26 '11 at 13:11