Auditing Spring Data Entities

Posted By :Deepak Singh Chauhan |26th February 2020

Spring data enables you to track who edited an item and when, with just a few annotations. When combined with Spring Security, you can set this metadata based on an active user.
 

Implementation
Here we  analyzes the persistence and configuration of audit metadata. It uses the active user to search associate Author once saving a Blogpost entity.


Entities & repositories
The Author class extends AbstractPersistable to obtain a primary key generated with appropriate equals (Object) and hashCode () implementations.
 

@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class Author extends AbstractPersistable<Long> {
  private String name;

  @CreatedDate
  @Temporal(TemporalType.TIMESTAMP)
  private Date createdDate;
}

The BlogPost class in turn extends AbstractAuditable with arguments of type <Author, Long>, to add Author createdBy () and Date createdDate (), as well as the Author modifiedBy () and Date modifiedDate () methods. In the database, the relationship between the BlogPost and Author tables will be captured as a foreign key.

@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class Blogpost extends AbstractAuditable<Author, Long> {

  private String title;
  private String content;
  private boolean published;

}

Both entities are annotated with @EntityListeners (AuditingEntityListener.class), which is a JPA entity listener to capture audit information about persistent and updated entities.

Our repositories simply extend the Spring Data Repository interface to define the save and findByName methods.

 

Enable JPA Auditing
We define the AuditSecurityConfiguration class, which we annotate with @EnableJpaAuditing to enable JPA audit by creating annotations. This will activate Spring Data to generate audit metadata for your entities.

@Configuration
@EnableJpaAuditing
public class AuditSecurityConfiguration {
  @Bean
  AuditorAware<Author> auditorAware(AuthorRepository repo) {
    // Lookup Author instance corresponding to logged in user
    return () -> Optional.ofNullable(SecurityContextHolder.getContext())
      .map(SecurityContext::getAuthentication)
      .filter(Authentication::isAuthenticated)
      .map(Authentication::getName)
      .flatMap(repo::findByName);
  }
}

The AuditSecurityConfiguration class specifies an individual AuditorAware <Author> tab, necessary to find the corresponding author entity for the active user. Note that the return type matches the audit type argument specified in the Blogpost category.

 

Conclusion
With audit information automatically generated by Spring Data, it is ideally configured to keep track of who has modified entities and when. This audit information can also be used in owner access restrictions if desired.

 

Thank you


About Author

Deepak Singh Chauhan

Deepak is a bright Java Developer, having good skills in Java, Servlet and Spring MVC Framework. His hobbies are travel and explore new places and learning about new technologies .

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us