Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Transactions and Locking

Optimistic Locking with @Version

Prevent lost updates with Hibernate optimistic locking - the @Version column, OptimisticLockException, lock modes, and how to handle conflicts in web apps.

Two users open the same product page, both change the price, both press Save. Without protection the second save silently overwrites the first: a lost update. Locking every row while someone edits is impossible on the web, since a user may leave the form open for an hour. Optimistic locking assumes conflicts are rare, lets everybody read freely, and detects a conflict at write time.

Hibernate is not available in the browser, so the mapping and session code is read-only. The runnable programs run the exact SQL Hibernate generates for a versioned entity against H2, so you can see why a conflict is detected.

The @Version attribute

Java
@Entity
public class Product {
    @Id @GeneratedValue Long id;
    String name;
    BigDecimal price;

    @Version
    int version;            // also allowed: long, short, Integer, Long, Instant, Timestamp
}

Hibernate manages the version: it is 0 after the first insert and increases by one on each update. Never set it yourself. When you change a product and flush, Hibernate sends:

SQL
update product set name=?, price=?, version=? where id=? and version=?
--                                    new = old+1        old value we read

If another transaction updated the row in between, version in the database is already higher, the where clause matches zero rows, and Hibernate throws OptimisticLockException (wrapped as ObjectOptimisticLockingFailureException in Spring). Your transaction rolls back and nothing was overwritten.

Delete works the same way: delete from product where id=? and version=?.

Java The SQL behind a version check (stand-in for the generated statements)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Handling the conflict

OptimisticLockException is not a bug, it is information. Typical responses:

  1. Tell the user and reload: "Someone else changed this product. Review the current values and try again." Show the fresh data so they can merge.
  2. Retry automatically when the operation is idempotent and does not depend on what the user saw (for example "increment the counter"): re-read the row and apply the change again, a few times (see Retries, Deadlocks and Concurrency Patterns).
  3. Merge field by field if you can prove two edits touched different fields.

In a web application the version must travel with the form, otherwise the check only protects the short request:

HTML
<input type="hidden" name="version" value="${product.version}">

On submit, load the entity, compare the submitted version with the loaded one (or set it on a detached object and merge), and treat a mismatch as a conflict. A merge of a detached entity with a stale version throws as well.

DTOs and REST APIs expose the version as an ETag and require If-Match on PUT: a mismatch gives 412 Precondition Failed.

Version without a version column

If you cannot add a column, Hibernate can compare other columns instead:

Java
@Entity
@OptimisticLocking(type = OptimisticLockType.DIRTY)   // compare only the changed columns
@DynamicUpdate
public class Customer { ... }

ALL compares every column, DIRTY only the modified ones. Both are weaker and slower than a version column, so use them for legacy schemas only.

Lock modes

You can ask for a version check even when you did not change the entity, to protect a decision based on it:

Java
Order order = session.find(Order.class, 1L, LockModeType.OPTIMISTIC);
// commit fails if order.version changed after this read

session.lock(account, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
// bumps the version even though nothing changed, making other writers conflict

OPTIMISTIC re-checks the version at commit; OPTIMISTIC_FORCE_INCREMENT also increments it. The second is useful for an aggregate root: when you add a line to an order, you want concurrent edits of the whole order to conflict, so you force-increment the order's version even though only a child row changed.

Java Aggregate version bump (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Setting or copying version in code. Let Hibernate own it.
  • Using a @Version on a type that a JSON mapper rewrites as null: when a detached entity arrives with version = null, Hibernate treats it as new.
  • Catching the exception and ignoring it. The user then believes the save worked.
  • Swallowing conflicts with automatic retries of non-idempotent operations (charging a card twice).
  • Bulk HQL updates that skip the version (use update versioned, see HQL Functions, CASE Expressions and Bulk Operations).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Hibernate add to the update statement for a versioned entity?

    The where clause carries the version read earlier. Zero updated rows means another transaction changed it, and Hibernate throws.
  2. 2. Who should set the @Version field?

    Hibernate increments it. Setting it yourself breaks conflict detection.
  3. 3. What is the best reaction to an OptimisticLockException in an edit form?

    The exception signals a real concurrent edit; the user decides how to reconcile.
  4. 4. When is LockModeType.OPTIMISTIC_FORCE_INCREMENT useful?

    It makes concurrent changes to the whole aggregate conflict, even if the root row itself was not modified.

Summary

  • @Version turns every update and delete into a compare-and-set; zero rows means a conflict.
  • Treat the exception as information: reload, merge, or retry idempotent operations.
  • Send the version with forms and ETags, otherwise only the short request is protected.
  • Lock modes OPTIMISTIC and OPTIMISTIC_FORCE_INCREMENT protect decisions and aggregates.

Next: Pessimistic Locking