Hibernate: Optimistic locking with @Version prevents lost updates

Two users editing the same row: the second commit fails instead of silently overwriting the first.

Code
@Entity
class Order {
    @Id Long id;
    @Version Long version;    // Hibernate manages it
    BigDecimal total;
}
Output
update orders set total=?, version=2 where id=? and version=1

If another transaction already moved it to 2:
0 rows updated -> OptimisticLockException
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11