Hibernate: Pessimistic locking takes a database lock

Use it when a conflict is likely and retrying is worse than waiting - stock counters, for example.

Code
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select p from Product p where p.id = :id")
Product findForUpdate(@Param("id") Long id);
Output
select ... from products where id=? for update

Other transactions block until this one commits.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11