0 day streak
java / intermediate
Snippet

Optimistic Locking with @Version

Optimistic locking prevents concurrent updates from overwriting each other. The @Version field tracks changes; if two threads try to update the same row simultaneously, one will throw an ObjectOptimisticLockingFailureException.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
@Entity
public class InventoryItem {
@Id @GeneratedValue
private Long id;
@Version
private Long version;
private Integer stockLevel;
}
spring
Breakdown
1
@Version
Tells Spring Data JPA to use this field for version tracking during database updates.
2
private Long version
Every time the entity is updated, Spring automatically increments this value in the database.