The @Version annotation marks the attribute that JPA uses for optimistic locking. Every update or delete adds the version value to the SQL WHERE clause and increments it. If another transaction changed the row first, no row matches, and the persistence provider throws an OptimisticLockException instead of silently overwriting the other change.
This is how JPA prevents the "lost update" problem without holding database locks while a user is thinking. This article shows how the check works, what the exception looks like in Spring, and when to prefer pessimistic locking.
Two users open the same product page. Both read the row with stock = 10. User A sells 3 units and saves 7. User B, still holding the old copy, sells 2 units and saves 8. Without any control, the last write wins and the sale of A disappears.
Pessimistic locking prevents this by locking the row on read. That is safe but holds locks across user think time and can cause deadlocks. Optimistic locking assumes conflicts are rare, lets everyone read freely, and detects the conflict at write time. @Version is the JPA mechanism for it.
Consider this entity (Jakarta Persistence, used by Hibernate 6 and 7 and Spring Boot 3 and 4):
When you change stock and the transaction flushes, the provider issues SQL like this:
The provider checks the number of affected rows. One row means success, and the in-memory version becomes 4. Zero rows means somebody else already moved the row to another version, so the provider throws an exception and the transaction rolls back. Deletes use the same WHERE id = ? AND version = ? condition.
The version is managed by the provider. Your code should never set it by hand, and the field normally has no setter.
| Type | Notes |
|---|---|
long / Long | Best default. Increments by one, never ambiguous. |
int / Integer, short / Short | Works, but can overflow on very hot rows. |
java.sql.Timestamp | Timestamp-based. Precision and clock issues make it weaker than a counter. |
Newer JPA versions (3.2 and later) allow more temporal types, but a numeric counter remains the recommended choice. An entity should have only one @Version attribute, and it must be on the entity class or a mapped superclass, not on an embeddable.
With Spring Data JPA, a conflict shows up as an ObjectOptimisticLockingFailureException (a subclass of OptimisticLockingFailureException), because Spring translates the persistence exception. The following test-style example shows two overlapping updates:
Retrying is only correct when the whole unit of work is re-read inside the retried transaction, which is why sell is its own transactional method and the retry loop sits outside it. For web requests, the usual alternative is to return HTTP 409 Conflict and let the client reload the data.
The version in a session only protects you while the entity stays loaded. In a typical REST flow you read in request one and update in request two, so the version has to travel with the data:
Without that explicit comparison, the provider only compares against the version it just loaded, and a stale client update would be accepted. A common variant exposes the version as an ETag and requires If-Match on updates. Merging a detached entity with EntityManager.merge() does compare the detached version, which is why detached entities must keep their version value.
You can also ask for version checks on entities you only read, using LockModeType:
| Lock mode | Effect |
|---|---|
OPTIMISTIC | At commit, verifies the version is unchanged. |
OPTIMISTIC_FORCE_INCREMENT | Increments the version at commit even if the entity was not modified. |
PESSIMISTIC_WRITE | Takes a database row lock (SELECT ... FOR UPDATE). |
OPTIMISTIC_FORCE_INCREMENT is useful on an aggregate root when a change to a child collection should count as a change to the parent.
Bulk JPQL updates such as UPDATE Product p SET p.stock = 0 bypass the persistence context and do not touch the version. Hibernate supports update versioned in HQL for this case, or you can increment p.version yourself in the query.
| Aspect | Optimistic (@Version) | Pessimistic |
|---|---|---|
| Locks held | None while reading | Row lock until commit |
| Best when | Conflicts are rare | Conflicts are frequent and costly |
| Failure mode | Exception and retry at write | Waiting, timeouts, deadlocks |
| Works across requests | Yes, with a version in the payload | No |
No. It detects conflicting writes to the same row. It does not protect invariants that span several rows, and reads can still be stale. For those cases use stronger isolation levels or explicit locking.
The persistence provider increments it when it flushes an update. Do not change it in your code.
Either works. With Spring Data, a wrapper such as Long that is null for new entities also lets the repository decide whether to call persist or merge.
In plain JPA it is jakarta.persistence.OptimisticLockException. In Spring, catch OptimisticLockingFailureException.
@Version adds a version column to every update and delete condition, so a stale write affects zero rows and fails loudly instead of overwriting newer data. Use a long counter, carry the version through your API, handle the conflict with a retry or an HTTP 409, and remember that bulk updates skip the check.