In JPA
, the use of @Version
allows us to use Optimistic Locking
wherein no real locks are actually applied to the database when updating records.
@Version
@Version
prevents data loss – simply put, one user may override another user’s changes especially when they are modifying the same data.
Sample Usage with @Entity
1 2 3 4 5 6 7 8 9 10 11 12 | @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; ... @Version private Integer version; ... } |
How does it work?
The field annotated with @Version
is checked against the actual table field before being updated for any change through JPA
. If the version of a Student object is not the same as that of the actual table field, a javax.persistence.OptimisticLockException
is thrown. I avoided data loss by preventing outdated copies of an Entity object from being used to update a database record.