Skip to content
javahacks.dev
Hibernate

How to Handle Lost Updates and Concurrent Updates in JPA

Reproduce a lost update in JPA with two transactions, then fix it with a version column, an atomic update query or a pessimistic lock, and test the conflict.

6 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, Spring Boot, Linux and IntelliJ IDEA logos.

Nothing in this story throws an exception. Alice opens an order, Bob opens the same order, Alice adds a note and saves, Bob changes the shipping address and saves, and Alice's note is gone. Both transactions were valid. Both committed. The database ended up in a state that neither user intended. This is the lost update, the most common concurrency bug in database applications, and it is the one that READ COMMITTED isolation, the default on most databases, does not prevent. This post reproduces it, shows three fixes and tests them. For the mechanics of the version column in more depth, read optimistic locking with a version column.

Reproduce it

An order entity with a note and an address, loaded and saved by two transactions that overlap:

src/main/java/dev/javahacks/orders/PurchaseOrder.javajava
package dev.javahacks.orders;

import jakarta.persistence.*;

@Entity
@Table(name = "purchase_order")
public class PurchaseOrder {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String note;
    private String shippingAddress;

    protected PurchaseOrder() {}

    public PurchaseOrder(String note, String shippingAddress) {
        this.note = note;
        this.shippingAddress = shippingAddress;
    }

    public Long getId() { return id; }
    public String getNote() { return note; }
    public void setNote(String note) { this.note = note; }
    public String getShippingAddress() { return shippingAddress; }
    public void setShippingAddress(String a) { this.shippingAddress = a; }
}
src/test/java/dev/javahacks/orders/LostUpdateTest.javajava
@SpringBootTest
@Testcontainers
class LostUpdateTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");

    @Autowired PurchaseOrderRepository orders;
    @Autowired PlatformTransactionManager tm;

    @Test
    void secondWriterOverwritesTheFirst() throws Exception {
        Long id = orders.save(new PurchaseOrder("none", "1 Old Street")).getId();
        var bothHaveRead = new CyclicBarrier(2);
        var tx = new TransactionTemplate(tm);

        Runnable alice = () -> tx.executeWithoutResult(s -> {
            var o = orders.findById(id).orElseThrow();
            await(bothHaveRead);
            o.setNote("gift wrap please");
        });
        Runnable bob = () -> tx.executeWithoutResult(s -> {
            var o = orders.findById(id).orElseThrow();
            await(bothHaveRead);
            o.setShippingAddress("2 New Street");
        });

        runBoth(alice, bob);

        var result = orders.findById(id).orElseThrow();
        System.out.println(result.getNote() + " | " + result.getShippingAddress());
    }
}
Text
none | 2 New Street

Alice's note, "gift wrap please", is gone. The reason is how Hibernate writes updates: the default UPDATE statement sets every column, so Bob's transaction wrote his stale copy of note back over Alice's change. Two reads, two writes, the second wins. There was no error to catch.

Fix 1: a version column

Add a @Version field and Hibernate includes the version in the WHERE clause of every update, incrementing it as it writes:

java
@Version
private long version;

The SQL for each save becomes update purchase_order set note=?, shipping_address=?, version=? where id=? and version=?. Alice commits first and the version goes from 0 to 1. Bob's update still says where version = 0, matches zero rows and Hibernate throws OptimisticLockException, which Spring surfaces as ObjectOptimisticLockingFailureException. Bob's work is rejected rather than silently destroying Alice's. The test now asserts the conflict:

java
assertThatThrownBy(() -> runBoth(alice, bob))
        .hasRootCauseInstanceOf(OptimisticLockException.class)
        .hasMessageContaining("Row was updated or deleted by another transaction");

What you do with the exception is a design choice. For a user editing a form, return 409 Conflict and show them the current state. For a background job that can safely redo its work, catch the exception and retry the whole transaction with a fresh read. Retrying needs the full transaction to run again, so annotate a method outside the transactional boundary, using Spring Retry or a loop, and not code inside it.

Fix 2: an atomic update

For counters and balances, the read is the problem. Instead of loading the row to compute the new value in Java, let the database do the arithmetic in one statement:

java
public interface StockRepository extends JpaRepository<StockItem, Long> {

    @Modifying
    @Query("update StockItem s set s.quantity = s.quantity - :n where s.sku = :sku and s.quantity >= :n")
    int decrement(@Param("sku") String sku, @Param("n") int n);
}
java
@Transactional
public void reserve(String sku, int n) {
    if (stock.decrement(sku, n) == 0) {
        throw new IllegalStateException("insufficient stock for " + sku);
    }
}

The statement is atomic. The database applies the decrement under its own row lock, the quantity >= :n condition guards the invariant, and the returned row count tells you whether it worked. There is no window between read and write, no version column, no retries. This is the best fix whenever the change is expressible as an expression on the stored value. The cost is that it bypasses the persistence context, so an entity already loaded in the same transaction does not see the change until you refresh it; the same warning applies to every bulk update, as in bulk updates and deletes in JPA.

Fix 3: a pessimistic lock

When the new value depends on a computation you cannot express in SQL, lock the row on read so the second transaction waits:

java
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select o from PurchaseOrder o where o.id = :id")
Optional<PurchaseOrder> findForUpdate(@Param("id") Long id);

Now Bob's read waits until Alice commits, then sees her note and his change merges on top of it. Nothing is lost, and no retry is needed, but Bob waits and a deadlock is possible if transactions lock several rows in different orders. The mechanics, timeouts and SKIP LOCKED are covered in using pessimistic locking in JPA.

Fix 4, partly: update only what changed

A fourth approach reduces the chance without eliminating it. Hibernate's @DynamicUpdate writes only the changed columns:

java
@Entity
@DynamicUpdate
public class PurchaseOrder { /* ... */ }

With it, Alice's transaction updates only note and Bob's only shipping_address, so in this specific example both changes survive. That is a real improvement for forms that edit different fields. It does not protect two writers who change the same column, and it generates SQL that varies per update, which defeats statement caching. Treat it as a mitigation and keep a version column for correctness.

Choosing

SituationFix
Counter, balance, stock levelAtomic update ... set x = x - :n where ...
User edits a record via a form@Version, return 409 on conflict
Background job that can redo its work@Version plus retry
Hot row, expensive to redo, short critical sectionPessimistic lock
Different users edit different fields of one row@Version, optionally with @DynamicUpdate

The fastest check on any entity is to ask whether two users can edit it at once. If the answer is yes and it has no @Version, add one. It costs a column and gives you a guarantee.

Test it for real

A lost update cannot be seen by a single threaded test, and a mock-based test only checks that you called the repository. Use two real transactions on a real database, as in the first example, and make the interleaving deterministic with a CyclicBarrier or CountDownLatch, so the test does not depend on timing luck. Assert the conflict exception for the versioned entity, and assert the final data for the atomic update. Repeating the test twenty times is cheap insurance, and Testcontainers means it runs against the same database engine as production, which matters because isolation behaviour differs between engines.

Surfacing the conflict to users

An optimistic locking failure is only useful if the user sees something sensible. Map ObjectOptimisticLockingFailureException to a 409 Conflict response with a message that says the record changed since it was loaded, and include the current version so the client can show a merge screen or reload. Avoid retrying automatically for edits a person made: retrying silently overwrites the other person's change, which is exactly the lost update the version column prevents. Automatic retries are right for background jobs that recompute their result from fresh data, and wrong for forms.

When this does not apply

If a single request is the only writer of a row, such as an immutable ledger row appended once, there are no lost updates to prevent. If you need conflict handling across services, the version has to travel with the API, for example as an ETag with If-Match, so a client can say "update version 4 only". That pattern is described in the HTTP semantics RFC 9110 section on conditional requests. For the underlying isolation behaviour, see SQL isolation levels and phantom reads, and for Hibernate specifics see the Hibernate documentation on optimistic locking.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.