Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How to Handle Optimistic Locking in JPA with @Version

Java
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedNov 15, 2024
UpdatedNov 16, 2026
7 min read

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.

Table of Contents

  • How optimistic locking works
  • Adding @Version to an entity
  • What happens when two transactions conflict
  • Handling OptimisticLockException with a retry
  • Explicit lock modes with LockModeType
  • Optimistic versus pessimistic locking
  • Frequently Asked Questions
    • Does @Version work without a database column?
    • Why does my bulk update not change the version?
    • Should I retry on OptimisticLockException?
    • Can I use a timestamp instead of a number?
  • Summary

How optimistic locking works

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:

sql

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.

Adding @Version to an entity

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).

java

Rules to follow:

  1. Declare only one @Version attribute per entity, in the root entity of an inheritance hierarchy.
  2. Never set the version yourself; the provider manages it.
  3. The column must be added to the table (for example version BIGINT NOT NULL DEFAULT 0).
  4. Only changes made through JPA update it. Bulk JPQL updates and native SQL bypass versioning unless you increment the version in the query (update Product p set p.price = ?1, p.version = p.version + 1 ...).

What happens when two transactions conflict

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.

java

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.

Handling OptimisticLockException with a retry

For short, automatic operations such as incrementing a counter, retrying the whole transaction is usually correct.

java

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.

Explicit lock modes with LockModeType

You can also request a lock mode explicitly:

Lock modeEffect
OPTIMISTICVerifies the version has not changed at commit, even for entities you only read.
OPTIMISTIC_FORCE_INCREMENTVerifies the version and increments it at commit, useful to protect aggregate roots when only child entities change.
PESSIMISTIC_READTakes a shared database lock.
PESSIMISTIC_WRITETakes an exclusive database lock, using SELECT ... FOR UPDATE.
java

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.

Optimistic versus pessimistic locking

AspectOptimisticPessimistic
Locks held in databaseNoYes, until commit
Best whenConflicts are rareConflicts are frequent
Conflict resultException on commitWaiting or timeout
ScalabilityHighLower
Needs version columnYesNo

Frequently Asked Questions

Does @Version work without a database column?

No. The version must be persisted in a column, because it is compared against the stored value on every update.

Why does my bulk update not change the version?

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.

Should I retry on OptimisticLockException?

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.

Can I use a timestamp instead of a number?

Yes, but a numeric version is more reliable, because two updates within the clock resolution can produce the same timestamp.

Summary

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.

Share