Java Reference
In-Depth Information
EntityManager em = ...;
String personPK = ...;
Person person = em.find(Person.class, personPK,
LockModeType.PESSIMISTIC_WRITE);
• Calling one of the EntityManager.refresh methods that takes the lock
mode as a parameter:
Click here to view code image
EntityManager em = ...;
String personPK = ...;
Person person = em.find(Person.class, personPK);
...
em.refresh(person, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
• Calling the Query.setLockMode or TypedQuery.setLockMode method,
passing the lock mode as the parameter:
Click here to view code image
Query q = em.createQuery(...);
q.setLockMode(LockModeType.PESSIMISTIC_FORCE_INCREMENT);
• Adding a lockMode element to the @NamedQuery annotation:
Click here to view code image
@NamedQuery(name="lockPersonQuery",
query="SELECT p FROM Person p WHERE p.name LIKE :name",
lockMode=PESSIMISTIC_READ)
Using Pessimistic Locking
Versioned entities as well as entities that do not have version attributes can be locked pess-
imistically.
To lock entities pessimistically, set the lock mode to PESSIMISTIC_READ ,
PESSIMISTIC_WRITE , or PESSIMISTIC_FORCE_INCREMENT .
If a pessimistic lock cannot be obtained on the database rows, and the failure to lock the
data results in a transaction rollback, a PessimisticLockException is thrown. If a
pessimistic lock cannot be obtained, but the locking failure doesn't result in a transaction
rollback, a LockTimeoutException is thrown.
Pessimistically locking a version entity with PESSIMISTIC_FORCE_INCREMENT res-
ults in the version attribute being incremented even if the entity data is unmodified. When
Search WWH ::




Custom Search