Enable auditing using Spring Data JPA

Manika Singh
2 min readMar 31, 2019

Auditing of entities in an application is a crucial part to store information about the updated time and authors of changes made to the entity. It helps us in tracking and logging user activity across the application.

If you are using spring data jpa, the task of maintaining the audit log becomes very easy since spring-data-jpa provides an efficient mechanism of achieving automatic auditing of entities. I am using a basic spring boot application to demonstrate how to achieve it.

I have created a class named Person which has fields like name, age, and gender. We want to store audit information like created date, last updated date, created by and last modified by of this entity. We can add the required columns in the same entity or can keep the auditing info in another class which all your other entities can extend.

First, we will add logging of created and modified dates which is pretty straight-forward. We can use @CreatedDate annotation for tracking created date, and @LastModifiedDate for tracking updated date. It takes the current system time and to store these values.

Next, we will implement created by and modified by for our entities. JPA can analyze createdDate and lastModifiedDate using current system time but how to tell JPA the author name for the changes.

In order for JPA to know about the currently logged-in user, we need to provide an implementation of AuditorAware and override getCurrentAuditor() method of the same. Then we can add the logic to fetch the currently logged in user. If you are using spring security you can get the currently logged in user from the security context principal object.

Next step is to enable auditing in our configurations. We can achieve that by annotating our configuration class with @EnableJpaAuditing. Then we need to create a bean of type AuditAware which will return our AuditAwareImpl instance. The name of the bean is passed to the auditorAwareRef argument of @EnableJpaAuditing to specify the implementation class.

Once the configuration is done we are all set to leverage the auditing functionality provided by spring data jpa. The final entity will have audit columns like this:

You can find a sample project for this implementation at Github.

--

--