When to use @Version and @Audited in Hibernate?

@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


@Version - is used to implement optimistic locking, see 2.2.1.2. Versioning for optimistic locking. Optimistic locking is useful when you don't expect many concurrent writes and don't want to pay the price of database locking.

@Audited - comes from Envers API and can be used to automatically track changes to entities in a separate auditing table. Use Envers to keep the history of changes of some of your entities.

Tags:

Hibernate