Skip to content
javahacks.dev
Hibernate

Fix StaleObjectStateException and Locking Failures

Why Hibernate throws StaleObjectStateException when two users edit one row, and how to handle it with versioning, retries or pessimistic locks.

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

Two people open the same order, both change a field and both press save. The second save fails with:

Text
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [dev.javahacks.shop.Order#17]

Spring Data surfaces it as ObjectOptimisticLockingFailureException. This is not a bug. It is the version check working, and what matters is what your application does next. The mapping and session behavior behind it are in the Hibernate and JPA guide.

How the check works

Adding @Version to an entity makes Hibernate append the version to every update and increment it:

java
@Entity
class Order {
    @Id @GeneratedValue private Long id;

    @Version private long version;

    private String status;
}
SQL
update orders set status = ?, version = 4 where id = ? and version = 3

If another transaction has already moved the version to 4, the where clause matches nothing, Hibernate sees zero updated rows and throws. Nothing was overwritten.

Cause 1: two users, one record

This is the case the feature exists for. Return a conflict to the client:

java
@RestControllerAdvice
class ConflictAdvice {

    @ExceptionHandler(ObjectOptimisticLockingFailureException.class)
    ProblemDetail conflict(ObjectOptimisticLockingFailureException e) {
        var problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
                "This record was changed by someone else. Reload it and try again.");
        problem.setTitle("Edit conflict");
        return problem;
    }
}

The version has to travel with the form. Send it to the client in the response, and have the client send it back:

java
Order order = orders.findById(id).orElseThrow();
if (order.getVersion() != request.version()) {
    throw new ObjectOptimisticLockingFailureException(Order.class, id);
}
order.setStatus(request.status());

Without that comparison, you reload a fresh entity with the latest version and the check can never fail, which silently loses the other user's change. The advice class pattern is the same one used in Spring MVC REST APIs.

Cause 2: concurrent background jobs

Two workers update the same row. A retry is correct here, as long as it reloads and recomputes:

java
@Retryable(retryFor = ObjectOptimisticLockingFailureException.class, maxAttempts = 3)
@Transactional
public void markShipped(long orderId) {
    Order order = orders.findById(orderId).orElseThrow();
    if (order.getStatus() == Status.PAID) {
        order.setStatus(Status.SHIPPED);
    }
}

Each attempt runs in a new transaction, reads the current state and decides again. Retrying a stale object would fail every time. Check that the operation is idempotent first.

Cause 3: the entity was deleted

Zero rows also means the row is gone. The message is identical, so look at the id in the brackets and check the table.

Cause 4: version in a merged detached entity

When you merge a detached entity with an old version, the update fails by design. If the stale version comes from a DTO you built yourself, you may have copied the wrong field. Compare the version in the log statement with what the database holds.

When to lock pessimistically instead

For a counter or an inventory row that many requests update, optimistic locking produces constant retries. A pessimistic lock serializes them:

java
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select p from Product p where p.id = :id")
Optional<Product> lockById(@Param("id") long id);

This issues select ... for update and holds the row until the transaction ends, so keep the transaction short and never call a remote service inside it. Locks that are taken in different orders across code paths cause deadlocks, which is a topic for the concurrency posts.

Reproduce the conflict deterministically

Concurrency bugs feel random until you script the interleaving. Two transactions load the same Account, the first saves a change, and the second saves a change based on the stale copy. The entity has a @Version field, and the code runs on Hibernate 7.2.25.Final, Spring Boot 4.0.9 and H2.

src/main/java/dev/javahacks/lab/Account.javajava
@Entity
public class Account {
    @Id @GeneratedValue Long id;
    String owner;
    long balance;
    @Version long version;
    // constructors and accessors omitted
}
java
Long id = tx.execute(s -> { Account acc = new Account("ada", 100); em.persist(acc); return acc.getId(); });

Account first  = tx.execute(s -> em.find(Account.class, id));    // version 0, balance 100
Account second = tx.execute(s -> em.find(Account.class, id));    // version 0, balance 100

first.setBalance(first.getBalance() + 10);
tx.executeWithoutResult(s -> em.merge(first));
System.out.println("first save ok");

second.setBalance(second.getBalance() - 30);
try { tx.executeWithoutResult(s -> em.merge(second)); }
catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); }
System.out.println("balance now " + tx.execute(s -> em.find(Account.class, id).getBalance()));
Text
first save ok
jakarta.persistence.OptimisticLockException: Row was already updated or deleted by another transaction for entity [dev.javahacks.lab.Account with id '1']
balance now 110

The first save succeeded and moved the version from 0 to 1. The second tried to update the row where id = 1 and version = 0, matched nothing, and Hibernate raised the exception because zero rows were changed. The last line is the point of the mechanism: the final balance is 110, the first writer's value, and the second writer's -30 was not silently applied on top of data it never saw. Without @Version, the same program would have ended with a balance of 70, and a deposit would have been lost without any error.

With a Spring Data repository the same condition surfaces as ObjectOptimisticLockingFailureException, because the repository proxy translates persistence exceptions. In a stack trace you may see either name, and the message carries the entity and its id, which tells you which row lost the race.

Retry the whole unit of work

Handling the exception by catching it and saving again would apply the old calculation to the old data. The correct retry reloads inside a fresh transaction and recomputes. Wrap the transactional call, not its inside.

java
public void withdraw(long accountId, long amount) {
    for (int attempt = 1; ; attempt++) {
        try {
            tx.executeWithoutResult(s -> {
                Account a = em.find(Account.class, accountId);     // fresh read each attempt
                if (a.getBalance() < amount) throw new InsufficientFunds(accountId);
                a.setBalance(a.getBalance() - amount);
            });
            return;
        } catch (OptimisticLockException | ObjectOptimisticLockingFailureException e) {
            if (attempt == 3) throw e;
            sleepBackoff(attempt);                                    // 10 ms, 20 ms, with jitter
        }
    }
}

Three attempts with a short randomised backoff covers ordinary contention. A conflict that survives three tries means the row is a hot spot, and the answer is a different design (an atomic update ... set balance = balance - ? statement, or a queue that serialises writes to that account), not more retries. Retrying is safe only because the business rule is re-evaluated on fresh data. If the operation has external side effects, such as sending an email inside the transaction, move them after the commit or the retry will repeat them.

Tell the client, with a status they can act on

When the conflict comes from a human editing a form, retrying silently would overwrite someone else's change, so the decision belongs to the user. Return 409 and carry the version.

java
@ExceptionHandler(ObjectOptimisticLockingFailureException.class)
ProblemDetail conflict(ObjectOptimisticLockingFailureException e) {
    ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
            "This record was changed by someone else. Reload it and apply your edit again.");
    p.setTitle("Edit conflict");
    return p;
}

Send the version to the client with the data, and require it back on update. A conflicting edit is then detected even across the minutes a person spends in a form, not just across the milliseconds of one request. Expose it as an ETag and read it from If-Match; a mismatch on that header is 412, the status designed for it.

Choose the mechanism by the contention you expect

Optimistic locking costs nothing when conflicts are rare and fails loudly when they happen, which suits most business data. Pessimistic locking, select ... for update through LockModeType.PESSIMISTIC_WRITE, makes other writers wait instead of fail, which suits a row that many transactions update in short bursts, such as an inventory counter. Its cost is held locks and the possibility of deadlocks, so keep such transactions short and always lock rows in a consistent order. When neither suits, an atomic update statement does the arithmetic in the database in one step and needs neither lock nor retry.

Observe locking failures in production

An optimistic lock failure is a normal event that tells you about contention, so count it. Increment a metric each time the exception is caught or handled, tagged with the entity type, and watch the rate. A steady trickle on one entity means a hot row, such as a counter, a shared configuration record or an order edited by several people. A sudden spike after a release points at a new code path that updates records it used to leave alone. Alert on the ratio of conflicts to successful updates for an entity, not on the absolute count.

When one entity shows a high rate, the design is the problem, and retry is only a patch. Split the hot data into separate rows (a counter per shard that is summed on read), move frequently updated fields out of the shared entity, or use an atomic update statement that does not need a version check at all.

Where this does not apply

If you update rows with bulk JPQL or native SQL, Hibernate's version check is bypassed. Add the version condition yourself. If a table has no version column and cannot get one, compare a timestamp or a content hash. The Hibernate documentation describes the locking modes in full. The Spring Data JPA reference documents the behavior in detail.

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.