To implement optimistic locking in JPA, add a @Version field to the entity. JPA then includes the version in every UPDATE and DELETE (WHERE id = ? AND version = ?) and throws OptimisticLockException if another transaction changed the row first. No database locks are held while users think or edit.
Use optimistic locking when conflicts are rare and you can ask the user to retry or merge. Use pessimistic locking when conflicts are frequent and retries are expensive.
Each row carries a version number. A transaction reads the row with version 5, edits it, and on flush runs UPDATE ... SET ..., version = 6 WHERE id = ? AND version = 5. If another transaction already moved the row to version 6, zero rows match, and the provider throws an exception instead of silently overwriting the other change (the "lost update" problem).
Supported types are int, Integer, long, Long, short, Short and java.sql.Timestamp (and in Hibernate also Instant and LocalDateTime). Prefer a numeric version over a timestamp, because timestamps can collide within the same clock tick. The provider manages the field; do not change it in your code. The package is jakarta.persistence in JPA 3 and later, and javax.persistence in older versions.
If two users load version 1 and both save, the first commit succeeds and the second fails:
Hibernate reports it as OptimisticLockException through the EntityManager, and Spring translates it to ObjectOptimisticLockingFailureException. Because the exception can surface at commit time, catch it outside the transactional method.
Retrying is right for operations that are safe to repeat, such as incrementing a counter. For user edits, return HTTP 409 Conflict and let the person reload and reapply the change. Spring Retry's @Retryable removes the loop boilerplate.
In a web application the entity is loaded in one request and saved in another, so the check must span them. Send the version to the client and send it back with the update.
Merging a detached entity that carries an old version also fails automatically, because the version field is compared during merge().
You can force a version check or increment even when the entity itself did not change.
| Lock mode | Effect |
|---|---|
OPTIMISTIC | Verifies the version has not changed at commit |
OPTIMISTIC_FORCE_INCREMENT | Also increments the version at commit |
Use force increment when a child change (for example a new order line) must invalidate concurrent edits to the parent aggregate. With Spring Data, add @Lock(LockModeType.OPTIMISTIC) to a repository method.
version = version + 1 yourself.@Version field there is no protection at all; the last writer wins.Yes. Hibernate generates the column if you use schema generation; otherwise add it in your migration, typically as BIGINT NOT NULL DEFAULT 0.
Optimistic for low contention and web apps. Pessimistic (PESSIMISTIC_WRITE) when many writers hit the same rows and retries are costly.
Not for normal use. The provider increments it on every successful update.
Yes. The version check is part of the update statement, so it works independently of the isolation level.
Add a @Version field, let JPA include it in updates, and handle OptimisticLockException by retrying or returning a conflict to the user. Carry the version through DTOs in web apps, use OPTIMISTIC_FORCE_INCREMENT for aggregates, and remember that bulk updates skip the check.