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 do you implement optimistic locking in JPA?

Java
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedNov 24, 2024
UpdatedNov 16, 2026
5 min read

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.

Table of Contents

  • How optimistic locking works
  • Adding a @Version attribute
  • What happens on a conflict
  • Handling the exception with a retry
  • Using the version across requests
  • Explicit lock modes
  • Limits to know about
  • Frequently Asked Questions
    • Does @Version need a database column?
    • Optimistic or pessimistic locking?
    • Can I set the version manually?
    • Does it work with isolation level READ COMMITTED?
  • Summary

How optimistic locking works

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

Adding a @Version attribute

java

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.

What happens on a conflict

java

If two users load version 1 and both save, the first commit succeeds and the second fails:

text

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.

Handling the exception with a retry

java

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.

Using the version across requests

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.

java

Merging a detached entity that carries an old version also fails automatically, because the version field is compared during merge().

Explicit lock modes

You can force a version check or increment even when the entity itself did not change.

Lock modeEffect
OPTIMISTICVerifies the version has not changed at commit
OPTIMISTIC_FORCE_INCREMENTAlso increments the version at commit
java

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.

Limits to know about

  • Bulk JPQL and native updates bypass the version unless you write version = version + 1 yourself.
  • It detects conflicts, it does not prevent them. Design the user experience for the failure.
  • Without a @Version field there is no protection at all; the last writer wins.
  • Distributed schemas need the version column in every table that is updated concurrently.

Frequently Asked Questions

Does @Version need a database column?

Yes. Hibernate generates the column if you use schema generation; otherwise add it in your migration, typically as BIGINT NOT NULL DEFAULT 0.

Optimistic or pessimistic locking?

Optimistic for low contention and web apps. Pessimistic (PESSIMISTIC_WRITE) when many writers hit the same rows and retries are costly.

Can I set the version manually?

Not for normal use. The provider increments it on every successful update.

Does it work with isolation level READ COMMITTED?

Yes. The version check is part of the update statement, so it works independently of the isolation level.

Summary

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.

Share