Could someone help me with the use case when to use @Version
and @Audited
in Hibernate?
The Envers project aims to enable easy auditing of persistent classes. All that you have to do is annotate your persistent class or some of its properties, that you want to audit, with @Audited . For each audited entity, a table will be created, which will hold the history of changes made to the entity.
In order to use optimistic locking, we need to have an entity including a property with @Version annotation. While using it, each transaction that reads data holds the value of the version property. Before the transaction wants to make an update, it checks the version property again.
When ever we use versioning then hibernate inserts version number as zero, when ever object is saved for the first time in the database. Next time when we update this object, hibernate increments that version no by one automatically . In hibernate mapping file, add an element called version soon after id element.
Version used to ensure that only one update in a time. JPA provider will check the version, if the expected version already increase then someone else already update the entity so an exception will be thrown.
@Version
is used to implement Optimistic locking with Hibernate, which means that no two transactions override the data at the same time with a conflict.
If the data is read by two threads at the same time, and both try to update the same row with different values, Hibernate uses the @Version
field to check if the row is already updated.
Before committing, each transaction verifies that no other transaction has modified its data. If modified, the last transaction encounters a "Working with stale data" error.
@Audited
is used to perform auditing functionality on entities part of Hibernate Envers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With