Persistence provider assumes database will hold short-term read locks and long-term write locks. Most persistence providers will delay database writes until the end of transaction unless explicit flush is called.
By default, optimistic locking is used.
Pessimistic locking is better when data is frequently accessed and modified by many transactions.
@Version protected int version;
types may be used: int, Integer, long, Long, short, Short, Timestamp
throws javax.persistence.OptimisticLockException if fail (data modified)
throws
PessimisticLockException if lock cannot be obtained and results transaction roll back
LockTimeoutException if fail to lock but doesn't result rollback
with force increment, result increased version even data not modified
when locking a optimistically locked entity, may throw OptimisticLockException
PESSIMISTIC_WRITE results version increment if transaction successfully committed
OPTIMISTIC: causes to check the version that were read (but not modified) as well as for entities that were updated
PESSIMISTIC: causes to immediately acquire long-term read or write locks for data corresponding to entity state
Set the lock mode :
EntityManager.lock(entityObject, mode)
EntityManager.find(Person.class, personPK, lockmode)
EntityManager.refresh(entityObject, mode)
Query.setLockMode() or TypedQuery.setLockMode()
@NamedQuery(name="xx", query="SELECT....", lockMode = )