Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use @Version and @Audited in Hibernate?

Tags:

hibernate

Could someone help me with the use case when to use @Version and @Audited in Hibernate?

like image 711
Kathir Avatar asked Nov 14 '12 07:11

Kathir


People also ask

What is @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.

How optimistic locking is implemented in hibernate?

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.

What is the use of hibernate versioning?

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.

What is @version in JPA?

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.


1 Answers

@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

like image 90
Jayendra Avatar answered Nov 11 '22 21:11

Jayendra