Video in progress

What is the field annotated with @Version for?

@Version turns on optimistic locking. On every UPDATE Hibernate checks and increments the version; if another transaction changed the row in the meantime, the UPDATE touches no rows and an OptimisticLockException is thrown.

📖 Answer

Adding one field to the entity is enough:

@Entity
public class Wallet {
    @Id private Long id;
    private BigDecimal balance;

    @Version
    private long version;
}

The SQL Hibernate sends on update:

update wallet set balance = ?, version = 6
where id = ? and version = 5

Two users read the same wallet at version 5 at the same time. The first one saves, and the version becomes 6. The second one's UPDATE can't match version = 5, so 0 rows change and Hibernate throws an error. That prevents a "lost update", where you overwrite someone else's change without knowing about it.

Things to know:

  • don't change the version field by hand;
  • the type can be long/Long/int or a timestamp (Instant); a number is more reliable;
  • after you catch the exception, you usually re-read the data and repeat the operation, or tell the user "the data has changed".

This approach holds no lock in the database, so it works well where conflicts are rare.