The @Lock annotation, from Spring Data JPA (org.springframework.data.jpa.repository.Lock), sets the JPA lock mode used when a repository query method runs. It takes a LockModeType value such as PESSIMISTIC_WRITE or OPTIMISTIC, so you can choose database-level locking or version checks per query without writing EntityManager code.
It is not a core JPA annotation. Plain JPA sets lock modes through EntityManager.find, EntityManager.lock or Query.setLockMode. Spring Data's @Lock is the repository-level shortcut for the same mechanism.
When two transactions load and change the same row, the later write can silently overwrite the earlier one (a lost update). Locking prevents this either by blocking the second transaction or by failing it. @Lock tells Spring Data which strategy to apply to the query on the annotated method.
You can place it on:
@Query;findByStatus;findById.With Hibernate on PostgreSQL, this issues select ... for update, which blocks other transactions that try to lock or modify the same row until yours commits or rolls back. In Spring Boot 2 and older the import is javax.persistence.LockModeType; Boot 3 and later use jakarta.persistence.
The value is a jakarta.persistence.LockModeType. The ones used in practice are:
| Mode | Strategy | Typical effect |
|---|---|---|
OPTIMISTIC | Optimistic | Version is checked at commit, fails if another transaction changed the row |
OPTIMISTIC_FORCE_INCREMENT | Optimistic | Version is incremented even if the entity was only read |
PESSIMISTIC_READ | Pessimistic | Shared lock, others can read but not write |
PESSIMISTIC_WRITE | Pessimistic | Exclusive lock, others wait to read for update or write |
PESSIMISTIC_FORCE_INCREMENT | Pessimistic | Exclusive lock plus a version increment |
NONE | None | No explicit lock (the default) |
READ and WRITE also exist as older synonyms of OPTIMISTIC and OPTIMISTIC_FORCE_INCREMENT. Prefer the explicit names in new code. The exact SQL depends on the database and Hibernate dialect, and not every database supports every mode.
Optimistic locking assumes conflicts are rare. The entity needs a version attribute:
Hibernate adds where version = ? to every update and increments the column. If another transaction changed the row first, the update affects zero rows and you get an OptimisticLockException (Spring translates it to ObjectOptimisticLockingFailureException). Plain @Version already protects updates. Add @Lock(LockModeType.OPTIMISTIC) to a read-only query when you need the version re-verified at commit even though you did not change the entity, for example when a decision depends on the row you read.
A common recovery pattern is to catch the exception and retry the whole transaction a limited number of times.
Use pessimistic locking when conflicts are likely and a failed retry is expensive, such as stock decrements or balance transfers.
The hint jakarta.persistence.lock.timeout (milliseconds) limits how long the query waits for the lock. When it expires you get a PessimisticLockException or LockTimeoutException. Some databases ignore the hint, so test on your own database. Always take locks in a consistent order (for example by ascending id), otherwise two transfers locking the same two accounts in opposite order can deadlock.
Locks live only as long as the transaction. A locking query called outside a transaction either throws TransactionRequiredException or locks nothing useful. Annotate the service method:
The lock is held until the method returns and the transaction commits. Keep such transactions short, and never call remote services while holding a row lock.
@Version.update ... set stock = stock - 1 where stock > 0) instead of locking at all.No. It is a Spring Data JPA annotation. The LockModeType it uses comes from Jakarta Persistence.
Yes. Database locks exist only within a transaction, so call the repository method from a @Transactional service method.
It depends on the database. In PostgreSQL and MySQL InnoDB, ordinary consistent reads are not blocked, but other for update or write attempts wait.
You receive a PessimisticLockException or LockTimeoutException, wrapped by Spring in an exception such as CannotAcquireLockException. Handle it by retrying or returning a clear error.
@Lock in Spring Data JPA selects the LockModeType for a repository query. Use OPTIMISTIC with @Version when conflicts are rare, and PESSIMISTIC_WRITE with a timeout when they are common. Always run locking queries inside a short transaction and acquire locks in a consistent order.