top of page
Search
Writer's pictureLeonard Anghel

How To Setup Spring Data JPA Auditing

Updated: May 10, 2020

Motivation:

Tracking user activities can be elegantly done via Spring Data JPA Auditing support. There is no need to do implement by yourself.


Description:

Auditing is useful for maintaining history records. This can later help us in tracking user activities.


Key points:

  • Create an abstract base entity (e.g., BaseEntity) and annotate it with @MappedSuperclass and @EntityListeners({AuditingEntityListener.class})

  • In this base entity, add the following fields that will be automatically persisted:

- @CreatedDate protected LocalDateTime created;

- @LastModifiedDate protected LocalDateTime lastModified;

- @CreatedBy protected U createdBy;

- @LastModifiedBy protected U lastModifiedBy;

  • Enable auditing via @EnableJpaAuditing(auditorAwareRef = "auditorAware")

  • Provide an implementation for AuditorAware (this is needed for persisting the user that performed the modification; use Spring Security to return the currently logged-in user)

  • Expose this implementation via @Bean

  • Entites that should be audited should extend the base entity

  • Store the date-time in database in UTC (GMT)

Tam Ta Da Dam! :) The complete code is available on GitHub.


If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices".



651 views0 comments

Recent Posts

See All

How To Bulk Updates

Motivation: This article is useful if you need a fast way to update a significant amount of data in the database. Bulk operations...

Comments


bottom of page