Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
Liam sets ticket 7 to URGENT, then Sophia saves her stale copy and the URGENT is gone with no error. One @Version field turns that silent lost update into an exception you can catch, reload and explain.
What you will learn
- Reproduce a lost update when two users save the same row
- Add a @Version column and read the 'where id and version' update
- Catch ObjectOptimisticLockingFailureException, reload and tell the user
- Compare last write wins, optimistic and pessimistic locking
Before you start
- Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
- Flyway Migrations in Spring Boot
Liam and Sophia are two support agents. Both open ticket 7 at the same moment. It's OPEN, priority HIGH, and each of them now holds a copy.
- Liam sets the priority to
URGENTand saves. The row saysOPEN, URGENT. - Sophia, still holding her old copy, sets the status to
IN_PROGRESSand saves. Her copy still saysHIGH.
The row ends up IN_PROGRESS, HIGH. Liam's change is gone, and nobody got an error. This is a lost update, and the table looks perfectly normal afterwards.
Reproduce it
To get two agents in one program, the runner uses two TransactionTemplates. Liam's has PROPAGATION_REQUIRES_NEW, so his save commits on its own while Sophia's transaction is still open:
/** Liam and Sophia edit ticket 7 at the same moment. */
@Component
public class TwoAgentsRunner implements CommandLineRunner {
private static final long TICKET = 7;
private final TicketRepository tickets;
private final TransactionTemplate sophia; // Sophia's transaction
private final TransactionTemplate liam; // Liam's own, separate transaction
private final boolean handle; // relay.handle: catch the failure or let it crash the run
public TwoAgentsRunner(TicketRepository tickets, PlatformTransactionManager tm,
@Value("${relay.handle:false}") boolean handle) {
this.tickets = tickets;
this.sophia = new TransactionTemplate(tm);
this.liam = new TransactionTemplate(tm);
this.liam.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
this.handle = handle;
}
@Override
public void run(String... args) {
say("Ticket #7 at the start: " + row());
try {
sophia.executeWithoutResult(tx -> {
Ticket hers = ticket(); // Sophia opens it
liam.executeWithoutResult(other -> { // Liam too
ticket().changePriority(Priority.URGENT);
}); // Liam saves
say("Liam saved: priority URGENT");
hers.changeStatus(Status.IN_PROGRESS);
}); // Sophia saves
say("Sophia saved: status IN_PROGRESS");
} catch (ObjectOptimisticLockingFailureException ex) {
if (!handle) {
throw ex; // the run crashes
}
say("Sophia: someone else changed ticket #7. Reloading.");
}
say("Ticket #7 now: " + row());
}
// ticket() = findById(7), row() = "status, priority", say() = println
}
Without any version, the console shows:
Ticket #7 at the start: OPEN, HIGH
Liam saved: priority URGENT
Sophia saved: status IN_PROGRESS
Ticket #7 now: IN_PROGRESS, HIGH
Both saves "worked". In the SQL log, both updates end with just where id=?, so the second one simply overwrites the first. Last write wins.
The fix: one field and one column
@Version
private long version;
@Version (from jakarta.persistence) tells Hibernate this field is the row's version number. It starts at 0 and Hibernate adds one on every update. Flyway adds the column in V3__ticket_version.sql:
alter table ticket add column version bigint not null default 0;
Run again (after resetting the row). Now both updates in the log end with where id=? and version=?, and the run stops:
ObjectOptimisticLockingFailureException: Unexpected row count (expected row count 1 but was 0) ...
Why zero rows match
Both agents read version 0. Liam's update says "where id is 7 and version is 0". One row matches, and the version rolls to 1. Sophia's update carries the same old version 0, but the row is at 1 now, so nothing matches. Hibernate expected one changed row, got zero, and Spring throws. Nothing was overwritten:
select id, status, priority, version from ticket where id = 7;
-- OPEN, URGENT, version 1
Catch it, reload, tell the agent
An exception protects the data, but an agent needs a friendly message. That's the catch in the runner above. With --relay.handle=true:
Sophia: someone else changed ticket #7. Reloading.
Ticket #7 now: OPEN, URGENT
Sophia gets a clear message, the reload reads the fresh row with Liam's URGENT and version 1, and she can make her change again on top of it.
In the Relay web app it's the same idea. Liam's page still shows "nobody assigned" because he opened ticket 7 earlier. Meanwhile Sophia saved first. When Liam clicks Assign, the save is stopped with an HTTP 409, and a red banner says someone else changed this ticket. His page carried the old version, so the check refused it.
Break it: remove @Version
Comment out @Version and the field, reset the row, run with --relay.handle=false. No error at all, and Ticket #7 now: IN_PROGRESS, HIGH. The lost update is back. Without a version, the last save always wins.
Three ways to share one ticket
| Approach | The second save | Cost |
|---|---|---|
Last write wins (no @Version) | overwrites the first; the change is lost | nothing, until it bites |
Optimistic locking (@Version) | fails; reload and try again | one column |
| Pessimistic lock | waits until the first one is done | held locks, waiting users |
Most tickets are edited by one person at a time. A version number catches the rare clash and costs almost nothing, which is why Relay uses it.
Common mistakes
- Adding the field but not the column. With
ddl-auto: validate, the app won't start. Add the Flyway file. - Setting the version yourself. Hibernate owns it. Never write to it in your code.
- Swallowing the exception. Catch it to reload and explain, not to pretend the save worked.
- Dropping the version on the way to the browser. A web page must send back the version it loaded, or the server can't detect the clash.
Try it yourself
Swap the agents in the runner: Sophia saves first, Liam second. Who gets the error now, and what does the row look like at the end?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
