Video in progress

Middle 🌱 Spring

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, so updatedAt doesn't change. In such queries, set the field yourself;
  • background jobs: in @Scheduled or a Kafka listener the SecurityContext is empty, and createdBy is null. AuditorAware can return "system" in that case;
  • time zone: storing Instant or OffsetDateTime instead of LocalDateTime is more reliable, otherwise times get confused when servers are in different zones;
  • if @EnableJpaAuditing sits on the main class, unexpected errors can appear in @DataJpaTest and @WebMvcTest tests, 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.