How to Use Optimistic Locking With a JPA Version Column
Use optimistic locking with a JPA version column: map @Version, handle OptimisticLockException, retry safely and expose the version through a REST API.

Two users open the same product page in the admin console. One sets the stock to 40 and saves. A minute later the other changes the name and saves, and the stock goes back to the old value, because the form posted every field. Nobody sees an error, and the first change is gone. That is a lost update, and optimistic locking is the standard way to detect it without holding any database lock while people think. The examples use Hibernate 7 and Spring Boot 4.
Map the version
@Entity
public class Product {
@Id @GeneratedValue
private Long id;
@Version
private long version;
private String name;
private int stock;
}When the entity is updated, Hibernate adds the version to the statement and increments it:
update product set name = ?, stock = ?, version = 4 where id = ? and version = 3If another transaction already moved the row to version 4, the where clause matches nothing, Hibernate sees zero updated rows and throws OptimisticLockException. Through Spring's exception translation the error appears as ObjectOptimisticLockingFailureException, which is the type you catch in a Spring service. Never write to the field yourself. Use a long, an int or a Instant: integers are simpler, since a timestamp column has finite resolution and two writes in the same tick would share a value. The older exception that reports this failure is described in StaleObjectStateException.
One detail catches new users. The version only protects what Hibernate wrote. A native SQL update, or a JPQL bulk update, bypasses the check unless you add version = version + 1 to it yourself, and a second application writing to the same table without the column breaks the contract entirely. Treat the version as a convention every writer must follow.
Handle the conflict on the server
@Retryable(retryFor = ObjectOptimisticLockingFailureException.class, maxAttempts = 3)
@Transactional
public void reserve(long productId, int qty) {
Product p = repository.findById(productId).orElseThrow();
p.setStock(p.getStock() - qty);
}A retry is only correct when the whole unit of work starts again: a new transaction, a fresh read of the row, and the change recomputed from what was read. Here reserve re-derives the new stock from the current value, so repeating it is safe. Retrying a call that reuses the stale entity from the first attempt loops until the attempts run out. The annotation works through a proxy, so the retry must wrap the transactional call from outside, which in practice means the method is invoked from another bean. If both annotations sit on one method, check the order in which the interceptors apply, because the retry has to be the outer one.
Be careful with side effects inside the retried block. An email sent before the exception is thrown is sent again on the next attempt. Move the side effect after the commit, for example with a transactional event listener.
Count your attempts. When a hot row needs more than three retries to get through, the retries are a symptom, and the next section applies.
Handle the conflict at the client
A form that loads a record, lets a person edit it for a minute and posts it back needs the version the person saw. Re-reading at save time defeats the purpose, since the second read would always match.
@GetMapping("/products/{id}")
ResponseEntity<ProductDto> get(@PathVariable long id) {
Product p = service.find(id);
return ResponseEntity.ok().eTag("\"" + p.getVersion() + "\"").body(ProductDto.from(p));
}
@PutMapping("/products/{id}")
ProductDto update(@PathVariable long id,
@RequestHeader("If-Match") String ifMatch,
@RequestBody ProductDto dto) {
return service.update(id, parseVersion(ifMatch), dto);
}In the service, load the entity and compare the supplied version with its current one, or set the supplied version on the entity before saving so Hibernate performs the check in SQL. Compare in code and you get a clean exception message; set it and Hibernate does the work atomically with the update, which closes the small window between your comparison and the flush. A mismatch becomes 409 Conflict, or 412 Precondition Failed when the client sent If-Match, which is the more precise code. The header mechanics are in ETags and conditional requests. The response body for the 412 should tell the client to reload, and a good UI offers to show what changed instead of discarding the person's edits.
Bulk updates and the version
A JPQL statement such as update Product p set p.stock = 0 where p.discontinued = true does not touch @Version, so concurrent editors holding an older copy will not notice it. Add p.version = p.version + 1 to the statement when that matters. Hibernate provides update versioned in HQL for the same purpose.
When to lock pessimistically
If many writers fight over the same row, optimistic locking turns into a retry storm: each failed transaction does its work and throws it away. LockModeType.PESSIMISTIC_WRITE issues select ... for update, which serializes writers on the row and holds a connection for the transaction. Use it for hot counters or inventory with real contention, keep the transaction short and set a lock timeout through the jakarta.persistence.lock.timeout hint so a stuck holder does not freeze the queue. For ordinary admin edits the two writers are minutes apart and optimistic locking costs nothing. Transactions in general are covered in Spring transaction management.
Testing the guard
Write one test that loads the same entity in two transactions, changes both, commits the first, and asserts that the second commit throws. It takes ten lines and pins the behavior against the day somebody removes the annotation while cleaning up the entity or changes a column type. Without it the only symptom is a bug report about vanished edits, weeks later.
What the exception tells you, and what it does not
ObjectOptimisticLockingFailureException says that the row you hold is not the row that is stored. It does not say who changed it, what they changed or whether the two changes conflict in substance. Two editors changing different fields of the same product will still collide, because the version is per row. If that is too coarse for your screens, split the entity so independent concerns sit in separate rows, for example stock levels apart from descriptive text, or use @OptimisticLock(excluded = true) on a field that should not count as a change, such as a last viewed timestamp.
When a user hits the conflict, the best response is a three-way view: what they loaded, what they typed and what is stored now. A simpler UI reloads the form with the stored values and keeps their edits highlighted. Silently overwriting defeats the exercise, and a bare error message teaches people to copy their text before saving.
Transaction boundaries and the flush
The check happens at flush, not at the moment you call a setter. With the default flush mode that is just before commit, so the exception can surface from the commit itself, outside your method, in a @Transactional proxy. That surprises people who wrap a try and catch around the setter and see nothing. Catch it where the transaction commits, or call flush() inside the method when you want the failure at a known line. And remember that after the exception the persistence context is no longer usable, so a retry must begin a new transaction and not continue in the old session.
When this does not apply
Append-only tables and immutable rows have no lost updates, so a version column adds a write for nothing. A table updated by exactly one process in sequence has the same property. Everything above is specified in the Hibernate user guide on locking and the Jakarta Persistence Version annotation.


