Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

How does optimistic locking with @Version work in JPA, and what exception does a Spring application see on a conflict?

We add a version field annotated with @Version to the entity, and Hibernate increments it on every update and adds where version = ? with the value it read to the UPDATE statement. If another transaction changed the row in between, no row matches, and Hibernate throws an OptimisticLockException (StaleObjectStateException in Hibernate's own API), which Spring translates into ObjectOptimisticLockingFailureException. No database lock is held between the read and the write, so the caller handles a conflict by retrying or by telling the user.

Why this question is asked

Lost updates are among the most common concurrency bugs in business applications, and optimistic locking is the standard JPA tool against them. Interviewers ask about it early because it shows whether we understand what Hibernate actually sends to the database and what a Spring application sees when it fails. In this answer, we will recap the problem it solves, add @Version to an entity, watch the SQL it produces, trigger a conflict, look at the exceptions, and decide what the caller should do.

1The Problem: Two Writers, One Row

Imagine two clerks open product 7 at the same time. Both see stock 10. One sells 3 and saves 7; the other sells 2 and saves 8. The second save silently overwrites the first, and the stock is wrong. This is a lost update: both transactions committed, and one change vanished.

We could prevent it by locking the row when reading, but then the second clerk waits for the first, and locks held while a human thinks are a bad idea. Optimistic locking takes the other view: assume conflicts are rare, let both work freely, and detect the conflict at the moment of writing.

2Adding @Version

We add one field to the entity. It can be a Long, Integer, Short or a timestamp type; a number is the usual choice because it is exact.

Java
@Entity
public class Product {
@Id
private Long id;
private String name;
private int stock;
@Version
private Long version; // managed by Hibernate, never set by our code
// getters and setters
}
// table: product(id, name, stock, version)
// a new product is inserted with version = 0

We do not write code that changes version. Hibernate owns it: it sets the initial value on insert and increments it whenever it updates the row.

3What Hibernate Sends to the Database

Now when we load the product, change it and the transaction commits, Hibernate builds the UPDATE with the version it read in the WHERE clause, and the next version in the SET clause.

Java
Product p = repo.findById(7L).orElseThrow(); // select ... -> stock 10, version 3
p.setStock(7);
// at commit:
// update product set name = ?, stock = 7, version = 4 where id = 7 and version = 3
// rows updated: 1 -> success, version is now 4
Step throughTwo transactions, one conflict
Clerk A txDatabaseClerk B tx
select product 7 -> version 3
select product 7 -> version 3
update ... version = 4 where version = 3
1 row updated, commit
update ... version = 4 where version = 3
0 rows updated -> conflict

6 messages in order. Play them, or step through them one at a time.

The second writer is detected, not blocked.

The key is the row count. The database reports how many rows the UPDATE changed. If it is 1, nobody changed the row since we read it. If it is 0, the row still exists but its version is no longer 3, so someone else updated it in between. Hibernate checks this count and treats 0 as a conflict. Notice that no lock was held while we worked: the check happens in the single UPDATE statement, which the database runs atomically.

4The Exceptions a Spring Application Sees

At the Hibernate level, the failed check raises StaleObjectStateException, Hibernate's own exception for an outdated entity. Through the JPA API it is reported as jakarta.persistence.OptimisticLockException. Spring's exception translation, which repositories and the JPA transaction manager apply, converts both into ObjectOptimisticLockingFailureException, part of Spring's DataAccessException hierarchy and a subclass of OptimisticLockingFailureException.

Java
try {
productService.sell(7L, 2);
} catch (ObjectOptimisticLockingFailureException e) {
log.info("conflict on {} id {}", e.getPersistentClassName(), e.getIdentifier());
}
// conflict on com.example.Product id 7

One detail matters for where we catch it: the UPDATE usually runs at flush, which often happens at commit, after our service method has returned. So the exception typically comes out of the transactional proxy, not out of the line that changed the entity. Code that wants to react to a conflict catches it around the call to the transactional method, not inside it.

5What the Caller Should Do

A conflict means our change was based on outdated data, so we must not simply save it again. There are two sensible reactions. If the change can be recomputed from fresh data, such as selling two units, we retry the whole transaction: load the product again, apply the change, commit. A loop of up to three attempts with a short random wait usually suffices. If the change came from a person editing a form, we report the conflict, for example with HTTP 409 Conflict and the current state, so they can review the other person's change and decide.

6Follow-up questions

Does a Spring Data save() of a detached entity also check the version?

Yes. save() on an existing entity calls merge(), and if the detached object's version differs from the row's current version, Hibernate raises the same optimistic lock failure. This is how a version sent back by a client can be checked.

Can I use a timestamp instead of a number?

Yes, @Version works on timestamp types, but two updates within the clock's resolution can get the same value and the clocks of different servers can disagree. A numeric version has neither problem, so it is the better default.

Does @Version help with deletes?

Yes. Hibernate also adds the version to the WHERE clause of the DELETE, so deleting a row that someone else has changed since we read it fails with the same exception.

7Conclusion

In this answer, we saw that @Version makes Hibernate add the read version to every UPDATE and DELETE and increment it, so a row changed by someone else matches no rows and the conflict is detected. Hibernate reports it as StaleObjectStateException or OptimisticLockException, Spring translates it to ObjectOptimisticLockingFailureException, no database lock is held between read and write, and the caller retries recomputable work or reports the conflict to the user.

What to say in the interviewAbout 80 seconds aloud

Open with

Optimistic locking with @Version detects lost updates without holding locks. I add a field like @Version private Long version to the entity, and Hibernate manages it: it starts at zero on insert and increments on every update.

Then, if they want more

The important part is the SQL: Hibernate writes update product set stock = ?, version = 4 where id = 7 and version = 3, using the version it read. If another transaction updated the row in the meantime, the version no longer matches, the update affects zero rows, and Hibernate treats that as a conflict.

In Hibernate's API that is StaleObjectStateException, through JPA it is OptimisticLockException, and Spring translates it to ObjectOptimisticLockingFailureException, a subclass of OptimisticLockingFailureException. Because the update usually happens at flush or commit, the exception comes out of the transactional method call, so that is where I catch it.

Nothing is locked between the read and the write, which is why it suits user edits and low-contention data.

On a conflict, I either retry the whole transaction with fresh data when the change can be recomputed, like decrementing stock, or return a 409 to the user when they edited something by hand, so they can see the other change before deciding.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does optimistic locking with @Version work in JPA, and what exception does a Spring...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/00370b2cfd/