Java, Software Development

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 especially 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. I avoided data loss by preventing outdated copies of an Entity object from being used to update a database record.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like