Video in progress

How do you enable audit fields like `@CreatedDate` and `@LastModifiedBy` in Spring Data JPA, and when do they stop working?

You need @EnableJpaAuditing, @EntityListeners(AuditingEntityListener.class) on the entity, and an AuditorAware bean that supplies the user. They work in JPA lifecycle callbacks, so the fields aren't updated for changes made through a bulk JPQL update, native SQL or StatelessSession.

📖 Answer

The setup:

@Configuration
@EnableJpaAuditing
class AuditConfig {
    @Bean
    AuditorAware<String> auditor() {
        return () -> Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                             .map(Authentication::getName);
    }
}

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
    @CreatedDate @Column(updatable = false) private Instant createdAt;
    @LastModifiedDate private Instant updatedAt;
    @CreatedBy @Column(updatable = false) private String createdBy;
    @LastModifiedBy private String updatedBy;
}

The listener runs on @PrePersist and @PreUpdate. So the fields are filled in only when the entity goes through Hibernate's usual path.

Where it silently doesn't work:

  • @Modifying @Query("update Order o set o.status = ..."): no entity is loaded, no callback is called, and updatedAt stays old. In such queries, add the field yourself: set o.updatedAt = CURRENT_TIMESTAMP.
  • Native SQL and rows written by other services.
  • In background jobs the SecurityContext is empty, so AuditorAware returns an empty Optional and createdBy is null. Give jobs a default value like "system".
  • If no field on the entity changes, @PreUpdate isn't called. That's correct behavior, but it sometimes prompts the question "why wasn't updatedAt updated?"

If you only need the time, Hibernate's @CreationTimestamp/@UpdateTimestamp annotations are enough too. If you need a full history, these fields aren't enough: you need Envers or CDC.