I am using Hibenate Envers . Entities are audited successfully . Now i want to have the version number (just like REV) to get with entity so that on each update it get automatically update (just like @Version)
How I can do so?
Should I use @Version
with @Audited
?
Or can i get rev_id
with each entity get with latest revision?
Help please?
The answer really boils down to your use case and how you intend to acquire the value.
If you're wanting to issue Criteria, JPQL, or HQL queries to your ORM entity tables and you want to be able to obtain a numeric value that indicates how frequent that row has been modified, then you should use the @Version
annotation. This is a value that ORM maintains itself for optimistic locking but it can serve a dual purpose to indicate the number of times a row has been modified in some way. Of course, the downside is when the row is deleted, you loose that value.
By default, Envers will not track the @Version
annotated property in the audit schema. So if you have Envers storing data at deletion, be aware that you'll again loose that value when the ORM row is deleted unless you specifically enable the tracking of the optimistic locking attribute. To do so, you want to set org.hibernate.envers.do_not_audit_optimistic_locking_field
to false.
Lastly, if you want to use the Envers Query API and fetch snapshots of historical representations of your entity, then you can use the Query API in several ways to determine this too based on Envers revision number semantics.
The first way is to ask the Query API for a list of all Revisions associated with an Entity class and then fetch each entity snapshot at the relevent revision. The unfortunate part is this process requires that you double dip on database queries, so for frequently modified entities, this could have some performance concerns.
The second way is to leverage the forRevisionsOfEntity
method on the Envers Query API and specify the second argument as false. This second argument effectively controls the return type the method will provide you, where false will return an array of Object[]
where the object array contains 3 elements:
The benefit to this approach over the prior Envers way is that its a single query that returns a combination of the data together, making it easier to loop and process.
So in the end it really depends on what purpose you're trying to serve. If its a mere counter that you want to effectively access at any point using ORM, use @Version
. If you want it to be associated with the audit snapshot, enable the aforementioned property as a baseline. Then there is the Envers Query API to fetch the data in various ways.