I have joined a project that was built for a year with Spring and Hibernate with Agile methodology and it didn't use Spring Data and has its own user class (not descendent of org.springframework.security.core.userdetails.User
).
Auditing came up as a new feauture to be implemented. (It's not enough to log the what controllers were called, we have to log every DB field's change, and which user did it. One controller can cause a lot of DB fields to change.) What are my options?
I have been looking at Javers, Envers and Audit4j. Javers requires Spring Data, so it's out. Envers' only requirement is Hibernate, which is statisfied, but I still don't see how the User object will be passed to it from the controller (the User's auth token is in the request object).
Hibernate Envers only gives you versioning (what have happened to an object at what time), but it doesn't help you figuring out who did the change.
A simple solution to the who-part is to create two new fields on all objects that shall be audited (i.e. in a base class such as AbstractAuditableEntity): User createdBy;
and User lastModifiedBy;
. Add two methods (I'm assuming you're using Spring Security here):
@PrePersist
protected void setCreatedBy() {createdBy = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();}
@PreUpdate
protected void setCreatedBy() {lastModifiedBy = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();}