What is the best way to handle audits in Spring Boot?

Viewed 465

We track any action in the system so we use @EntityListeners(AuditListener.class) on entities that listen for any action.

code snippet:

public class AuditListener {

    @Autowired
    private AuditRepository auditRepo; 

    @PrePersist
    public void preSave(Object object) {
        // save audit to database
    }
}

so what is the best to use @PrePersist or @PostPersist?

1 Answers

As said by @aksappy, if you wish to audit before or after insert you'll have to choose. But you should know that @prePersist @postPersist are not the only one to take care of. There are also @preUpdate @postUpdate. I don't mentionned @preRemove @postRemove because it seems not possible to audit the remove action (I'm not sure of that one because I haven't tested it myself).

But I can't recommend you enough Hibernate Envers a mature library for auditing/versioning your entities. It's very straightforward to setup and once you are done, it's easy to use on every entities. It'll log every addition, modification and deletion that happen. It's useful when you also want to show history of what happen to an entity, everything is being take care of with the methods provided by Envers.

I suggest you take a look at this guide https://www.baeldung.com/database-auditing-jpa#hibernate and see by yourself. It shows you how to setup Hibernate Envers if you want to try it.

Related