Home » Framework » Create Audit Fields of an Entity in Spring Boot

Create Audit Fields of an Entity in Spring Boot

Audit Fields of Entity is used to identify when the entity has been created and who created it. As well as it identifies when the entity has been modified and who updated it.

Let's start to see how to create the audit fields in an entity in spring boot with the MongoDB application. Spring data provides the default audit fields configuration of any database. Let see how to implement it.

Spring data provides the annotation called @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate. We can use the annotations whatever we want. Here I configured entity with all four.

The below code shows how the Profile entity is configured with audit fields.

package com.tipstocode.model;
import java.time.LocalDateTime;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection  = "user_profile")
public class ProfileVO {	
	@Id
	private ObjectId _id;	
	private String firstName;	
	private String lastName;	
	private String mobile;	
	private String emailId;		
	@CreatedBy
	private String createdBy;
	@CreatedDate
	private LocalDateTime createdDate;
	@LastModifiedBy
	private String lastModifiedBy;
	@LastModifiedDate
	private LocalDateTime lastModifiedDate;
	//Getters and Setters are Here
}

@CreatedBy describes who created the entity, @CreatedDate describes when the entity has been created, @LastModifiedBy describes who modified the entity at last and @LastModifiedDate describes when that last modification happened.

In the place of createdDate or lastModifiedDate we can use any type of date. We can use Date, Calendar from java.util package or Joda time. Joda time is having more functionalities and that API also available in java.time package of Java 8.

If you are using java 7 and you may want to use Joda time then please include the maven dependency below in your pom.xml file.

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.6</version>
</dependency>

you can find the latest version of Joda time here

Enable Auditing in Spring Boot

Let see how to enable the audit functionalities in Spring Boot MongoDB application. Simply add the @EnableMongoAuditing in the main class.

In the Profile entity, I used LocalDateTime for createdDate and lastModifiedDate. Spring Data bind the date automatically when the creation of an entity and modifies when the update happens.

But we have to provide the user details of createdBy and lastModifiedBy of an entity. This info we can get from the securityContext if we are using spring security. Here I hard-coded the user name for example.

Let see how to provide the user info like user name to the field createdBy and lastModifiedBy. Spring data provides the AuditorAware interface to achieve that. Simply create any class which implements the AuditorAware interface like below.

package com.tipstocode.model;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
public class EntityAuditing implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        // get your user name here
    	return Optional.of("abc");
    }

}

The above configuration supplies the user name to the audit fields of createdBy and lastModifiedBy when the time of creation.

If you are using Spring Security then the configuration is like below.

package com.tipstocode.model;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
public class EntityAuditing implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
       String userName= SecurityContextHolder.getContext().getAuthentication().getName();
        return Optional.of(userName);
    }

}

the above code fetches the logged-in user name from the security context and supplies the same to corresponding audit fields. Now we have to enable these auditing features in the application.

Let's enable the mongo auditing by using @EnableMongoAuditing annotation. We have to put this annotation at the top of the class name. Then we have to make the AuditorAware Bean available in the main class of the Spring Boot application like below.

package com.tipstocode.springbootmongocrud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import com.tipstocode.model.EntityAuditing;

@SpringBootApplication
@ComponentScan(basePackages = {"com.tipstocode.*"})
@EnableMongoAuditing
public class SpringbootmongocrudApplication {	
	@Bean
    public AuditorAware<String> auditorAware(){
        return new EntityAuditing();
    }
	public static void main(String[] args) {
		SpringApplication.run(SpringbootmongocrudApplication.class, args);
	}
}

Note: While updating the entity the fields createdBy and createdDate are not getting updated. So if you want to update the same then you need to fetch the existing entity from DB based on id and set the values through the setter function before the update.

Hope you understood the audit fields configuration of an entity in Spring Boot with the MongoDB application. Download the full source code from GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *