liveBook · Manning

PESSIMISTIC_WRITE

As explained in Java Persistence with Spring Data and Hibernate epub

PESSIMISTIC_WRITE is a JPA lock mode that acquires an exclusive lock, guarantees repeatable reads, and serializes conflicting data access.

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.

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains guarantees, transaction lifetime, failure timing, provider behavior, and dialect-specific SQL, but defers offline lock implementations.
Examples
Uses EntityManager.find with a timeout and Hibernate-generated SELECT ... FOR UPDATE SQL.
What you can do after
Operate/configure JPA EntityManager locking with transaction boundaries, lock timeouts, and database-dialect considerations.
How it connects
Connects exclusive locks with JPA transactions, Hibernate, SQL dialects, optimistic locking, repeatable reads, and phantom reads.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.