java / expert
Snippet
Optimistic Locking with JPA @Version for Concurrency
Optimistic locking prevents 'lost updates' in concurrent environments. The @Version field is automatically checked by Hibernate during updates; if the version in the database has changed, an ObjectOptimisticLockingFailureException is thrown.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Entitypublic class Account {@Idprivate Long id;private BigDecimal balance;@Versionprivate Long version;public void withdraw(BigDecimal amount) {if (balance.compareTo(amount) < 0) throw new InsufficientFundsException();this.balance = this.balance.subtract(amount);}}
spring
Breakdown
1
@Version
Specifies the version field used for optimistic locking detection.
2
private Long version;
JPA uses this numeric field to track entity changes across transactions.