Spring Boot: Entity Events & Auditing¶
TL;DR / when to use this: Two ways to react to entity lifecycle in Spring Boot: JPA lifecycle annotations on the entity itself, or a separate listener class via @EntityListeners. For audit columns (createdBy, createdDate, ...), use the built-in AuditingEntityListener plus an AuditorAware implementation.
JPA lifecycle annotations¶
Available on any @Entity:
| Annotation | Fires |
|---|---|
@PrePersist / @PostPersist |
before / after insert |
@PreUpdate / @PostUpdate |
before / after update |
@PreRemove / @PostRemove |
before / after delete |
@PostLoad |
after load from DB |
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@PrePersist
public void beforePersist() {
// custom logic, e.g. setting default values
}
}
For separation of concerns, move the callbacks to a listener class (note the entity parameter) and associate it:
public class MyEntityListener {
@PrePersist
public void beforePersist(MyEntity entity) { /* ... */ }
}
@Entity
@EntityListeners(MyEntityListener.class)
public class MyEntity { /* ... */ }
AuditingEntityListener¶
Spring ships an auditing listener for the standard audit fields:
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Product {
@CreatedBy
private String createdBy;
@LastModifiedBy
private String updatedBy;
@CreatedDate
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime updatedDate;
}
Spring needs to know who the auditor is — implement AuditorAware:
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.of("system");
}
return Optional.of(authentication.getName());
}
}
Enable it with @EnableJpaAuditing on a config class.