Optimistic locking in JPA detects conflicting updates without holding database locks. You add a version attribute to the entity with @Version, and the persistence provider includes the expected version in every UPDATE ... WHERE id = ? AND version = ?. If another transaction changed the row first, no row matches and JPA throws an OptimisticLockException (surfaced in Spring as ObjectOptimisticLockingFailureException), so you can retry or tell the user.
This approach suits workloads where conflicts are rare and reads dominate. It scales well because no lock is held while users think, which is why it is the default choice for web applications.
Each entity row carries a version number. When you load the entity you also load its version. At flush time the provider issues something like this:
If the update count is 1, the change succeeded and the version is incremented. If it is 0, someone else committed a change after you read the row, and the provider throws an exception. Nothing is blocked in the meantime, so two users can edit the same record and the second to save gets the conflict.
The @Version attribute can be int, Integer, long, Long, short, Short, or a timestamp type such as java.sql.Timestamp and java.time.Instant. A numeric version is safer than a timestamp because clock resolution can hide quick successive updates. The examples use Jakarta Persistence (the jakarta.persistence package, used since Jakarta EE 9 and Spring Boot 3).
Rules to follow:
@Version attribute per entity, in the root entity of an inheritance hierarchy.version BIGINT NOT NULL DEFAULT 0).update Product p set p.price = ?1, p.version = p.version + 1 ...).Consider two users who load the same product at version 3. User A saves first and the row moves to version 4. User B then tries to save a change based on version 3.
User B's commit fails with jakarta.persistence.OptimisticLockException. With Spring Data JPA you will usually see org.springframework.orm.ObjectOptimisticLockingFailureException, which wraps the Hibernate StaleObjectStateException. The transaction rolls back, so none of User B's changes are saved.
Keep in mind that the exception may be thrown at flush or commit time, which is often after your service method returns. Catch it at the transaction boundary, not only inside the method.
For short, automatic operations such as incrementing a counter, retrying the whole transaction is usually correct.
The transactional method must live in another bean so the retry loop wraps the whole transaction, with a fresh read on each attempt. Spring Retry's @Retryable or Spring Framework 7's built-in retry support can replace the manual loop. For user-facing forms, do not retry silently: show a message such as "this record was changed by someone else" and let the user reload and reapply.
When you pass entities across requests (for example in a REST API), send the version to the client and send it back on update. Otherwise the check only covers the short time inside one transaction. With DTOs, copy the version into the loaded entity before saving, or use an ETag and If-Match header.
You can also request a lock mode explicitly:
| Lock mode | Effect |
|---|---|
OPTIMISTIC | Verifies the version has not changed at commit, even for entities you only read. |
OPTIMISTIC_FORCE_INCREMENT | Verifies the version and increments it at commit, useful to protect aggregate roots when only child entities change. |
PESSIMISTIC_READ | Takes a shared database lock. |
PESSIMISTIC_WRITE | Takes an exclusive database lock, using SELECT ... FOR UPDATE. |
With Spring Data JPA, annotate a repository method with @Lock(LockModeType.OPTIMISTIC). Use pessimistic locks only when conflicts are frequent, such as stock reservation under heavy load, because they hold database locks and can cause waits or deadlocks.
| Aspect | Optimistic | Pessimistic |
|---|---|---|
| Locks held in database | No | Yes, until commit |
| Best when | Conflicts are rare | Conflicts are frequent |
| Conflict result | Exception on commit | Waiting or timeout |
| Scalability | High | Lower |
| Needs version column | Yes | No |
No. The version must be persisted in a column, because it is compared against the stored value on every update.
JPQL bulk updates and native queries bypass the entity lifecycle. Increment the version column in the query yourself if later optimistic checks must see the change.
Retry for automated, idempotent operations. For user edits, report the conflict and let the user decide, since a silent retry could overwrite their colleague's changes.
Yes, but a numeric version is more reliable, because two updates within the clock resolution can produce the same timestamp.
Optimistic locking in JPA relies on a @Version field that the provider checks and increments on every update. A conflicting update affects zero rows and raises an optimistic lock exception, which you handle with a retry or a user message. Use it by default, move the version through your API so it covers the full edit cycle, and switch to pessimistic locks only for high-contention data.