PESSIMISTIC_WRITE is a JPA lock mode for exclusive database locking. It guarantees repeatable reads, prevents phantom reads, and requires the provider to serialize conflicting data access. section 11.2.3
Use it with these operational expectations:
- Hibernate commonly implements the lock by appending FOR UPDATE, although the exact SQL depends on the database dialect. section 11.2.3
- The lock lasts only for the surrounding database transaction and raises an exception when it cannot be acquired. section 11.2.3
- Unlike optimistic locking, it detects contention when the locking query runs rather than potentially waiting until commit. section 11.2.3
Lock an entity for update
EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Category category = em.find(Category.class, CATEGORY_ID, LockModeType.PESSIMISTIC_WRITE, hints); category.setName("New Name"); em.getTransaction().commit(); em.close(); With a supported dialect and a five-second timeout, this can execute as SELECT ... FOR UPDATE WAIT 5000.
