Video in progress
How do you automatically fill in createdAt, updatedAt and createdBy fields in Spring Data JPA?
Spring Data has auditing: you enable @EnableJpaAuditing, attach AuditingEntityListener to the entity, and put @CreatedDate, @LastModifiedDate and @CreatedBy on the fields. An AuditorAware bean tells it who the user is.
📖 Answer
@Configuration
@EnableJpaAuditing
class AuditConfig {
@Bean
AuditorAware<String> auditor() {
return () -> Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.filter(Authentication::isAuthenticated)
.map(Authentication::getName);
}
}
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
abstract class Auditable {
@CreatedDate @Column(updatable = false) Instant createdAt;
@LastModifiedDate Instant updatedAt;
@CreatedBy @Column(updatable = false) String createdBy;
@LastModifiedBy String updatedBy;
}
@Entity
class Invoice extends Auditable { ... }
You get rid of writing invoice.setCreatedAt(Instant.now()) in every service, and nobody forgets it.
Where people trip in practice:
- a bulk UPDATE (
@Modifying @Query) bypasses the entity listener, soupdatedAtdoesn't change. In such queries, set the field yourself; - background jobs: in
@Scheduledor a Kafka listener theSecurityContextis empty, andcreatedByisnull.AuditorAwarecan return"system"in that case; - time zone: storing
InstantorOffsetDateTimeinstead ofLocalDateTimeis more reliable, otherwise times get confused when servers are in different zones; - if
@EnableJpaAuditingsits on the main class, unexpected errors can appear in@DataJpaTestand@WebMvcTesttests, so it's better to move it into a separate configuration class.
This isn't a full audit log: if you need to keep who changed what with the history, you need Hibernate Envers or a separate audit table.
Sign up to mark studied questions and save your progress.