Issue
I need to audit all changes on some of my DB tables. For example, for a given Employee I need to know all addresses and the day that this field was modified. Actually I'm using Spring Data, Hibernate and JPA. A good option would be to use Hibernation Envers but the problem is that I can't get history records with Spring Data. The other option would be to have a Employee_history table but I don't see a way to grab Employee records from two different tables (I want to insert in Employee table but grab data from Employee and Employee_history). Is there any other way to accomplish this?
Solution
The first question you have to answer should be the level of auditing you need. Is a simple list of changes enough? Is a string representation good enough? Or do you want to be able to support revisions of your entity where you would be able to go back and fetch the data of revision X "without any hassle"?
If a list of changes is enough and you use hibernate anyway I would go for a HibernateEventListener
(not JPA), simply because you already get all the changes in the postevents. No need to create the delta yourself.
Envers on the other hand is quite easy to integrate and configure. Annotating your entities with @Audited is enough to get going with "full" revision support. The fact that you cannot directly use Spring Data to query the revision entities is secondary, in my belief, since you can always write your AuditReaderRepository
bean and use the hibernate audit query interface directly. Fiddling out the change list between two revisions would be left to you in this case, which basically means fetching the revisions and determining the delta between them. The main advantage of Envers in this case is that a user representation is still a User class and not just a String (creator f.e.)
It depends which level of auditing you like to support and I would go with the smallest needed implementation. There are some good blogs about what kind of auditing strategies to choose in the www.
Answered By - Martin Frey
Answer Checked By - Terry (JavaFixing Volunteer)