JPA – Optimistic Lock with @Version

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 prevents data loss – simply put, one user may override another user’s changes specially when they are modifying the same data.

Sample Usage with @Entity

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.

Data loss i avoided by preventing outdated copies of an Entity object from being used to update a database record.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert