To implement auditing with Spring Data JPA, add @EnableJpaAuditing to a configuration class, extend a @MappedSuperclass that carries @CreatedDate, @LastModifiedDate, @CreatedBy and @LastModifiedBy fields and @EntityListeners(AuditingEntityListener.class), and provide an AuditorAware bean that returns the current user. Spring Data then fills these fields on every save.
This article walks through a complete Spring Boot setup: dependencies, database migration, configuration, a REST example and a test that proves the fields are set. It assumes Spring Boot 3 or later and Java 17 or newer.
Spring Data JPA comes with the JPA starter. Add Spring Security only if you want the user from the logged-in principal.
For Gradle, use implementation 'org.springframework.boot:spring-boot-starter-data-jpa'. Spring Boot manages the versions, so you do not set them.
Let a migration tool such as Flyway or Liquibase own the schema in production instead of spring.jpa.hibernate.ddl-auto. A Flyway script for a task table looks like this.
Setting the columns NOT NULL makes a missing listener fail loudly instead of silently storing nothing.
Spring Data supports Instant, LocalDateTime, OffsetDateTime, ZonedDateTime, Long and the legacy java.util.Date for the date fields. Prefer Instant.
If you do not use Spring Security, return a fixed value or read the user from a request header through your own context holder. The auditor type, here String, must match the type of the @CreatedBy field. You can use a Long user id or a User entity reference instead.
On POST, all four audit fields are set. On PUT, only updatedAt and updatedBy change. Returning entities directly is shortened here for brevity. In real code, return a DTO that exposes only the fields clients need.
@WithMockUser comes from spring-security-test. This test would fail if @EnableJpaAuditing or the entity listener were missing, which is exactly the regression you want to catch.
@EnableJpaAuditing in Spring Boot?Yes. Spring Boot does not enable auditing automatically, so add the annotation to a @Configuration class or your main application class.
Yes. Implement AuditorAware to return any identifier you have, such as a value from a thread-local request context or a constant like "system".
updatedAt?Auditing runs through entity lifecycle callbacks. JPQL bulk updates and native SQL skip them, so set the column in the query yourself.
@Version and optimistic locking?Yes. Auditing fields and a @Version field are independent, and both are updated on each save.
Spring Data JPA auditing needs three pieces: @EnableJpaAuditing, a mapped superclass with audit annotations and AuditingEntityListener, and an AuditorAware bean for the user. Create the columns in a migration, use Instant, and add a test that asserts the fields are populated so the setup cannot break unnoticed.