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".
Comments