Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Set up Spring Data JPA auditing so entities get createdAt, updatedAt and createdBy filled automatically.

Enable auditing with @EnableJpaAuditing on a configuration class, register AuditingEntityListener on the entity with @EntityListeners, and mark fields with @CreatedDate, @LastModifiedDate, @CreatedBy and @LastModifiedBy, usually in a shared @MappedSuperclass. For the user fields, provide an AuditorAware<T> bean that returns the current user, for example from Spring Security's SecurityContext. Auditing runs through JPA lifecycle callbacks, so bulk updates and native queries bypass it.

Why this question is asked

Almost every business table needs to answer two questions: when was this row created and last changed, and by whom. Writing that code by hand in every service method is repetitive and easy to forget, which is how tables end up with null updated_at values. Spring Data's auditing fills these fields automatically. Interviewers ask for the setup to see whether we know all the pieces, how they connect, and where the automatic filling stops working. In this answer, we will recap how auditing works, enable it, write a base class with the audit fields, provide the current user with AuditorAware, see it fill the fields on insert and update, and look at the cases that bypass it.

1A Quick Recap: How Auditing Works

JPA has lifecycle callbacks: methods that run just before an entity is inserted (@PrePersist) or updated (@PreUpdate). An entity listener is a separate class whose callback methods JPA calls for the entity.

Spring Data provides one such listener, AuditingEntityListener. Before an insert, it sets the fields marked @CreatedDate and @CreatedBy, and also the last-modified fields by default; before an update, it sets @LastModifiedDate and @LastModifiedBy. It gets the time from a clock and the user from an AuditorAware bean we supply. The whole mechanism lives inside Hibernate's entity lifecycle, which is the key to understanding its limits.

2Enable Auditing

Auditing is off until we enable it. @EnableJpaAuditing on any configuration class registers the auditing infrastructure. The auditorAwareRef attribute names the AuditorAware bean; if there is exactly one, Spring finds it without the attribute.

Java
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
class JpaAuditingConfig { }

Keep this on a separate configuration class rather than the main application class. If it sits on the @SpringBootApplication class, test slices such as @WebMvcTest also try to enable JPA auditing and fail because there is no JPA infrastructure in that slice.

3A Base Class With the Audit Fields

Since many entities need the same four fields, we put them in a @MappedSuperclass, a class whose fields are inherited by entities and mapped into each entity's own table, without being an entity itself. The listener goes on the same class, so every subclass is audited.

Java
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
@CreatedDate
@Column(nullable = false, updatable = false)
private Instant createdAt;
@LastModifiedDate
@Column(nullable = false)
private Instant updatedAt;
@CreatedBy
@Column(updatable = false)
private String createdBy;
@LastModifiedBy
private String updatedBy;
public Instant getCreatedAt() { return createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public String getCreatedBy() { return createdBy; }
public String getUpdatedBy() { return updatedBy; }
}
@Entity
class Customer extends Auditable {
@Id @GeneratedValue Long id;
String name;
}

Notice updatable = false on the created fields. Auditing would not change them anyway, but the column setting also stops any update path from overwriting them. Instant, LocalDateTime and a few other date types are supported for the date fields.

4Provide the Current User With AuditorAware

AuditorAware<T> is a functional interface with one method, Optional<T> getCurrentAuditor(). T is the type of the createdBy fields, here String. With Spring Security, the current user is in the SecurityContext, a per-request holder of the authenticated principal.

Java
@Bean
AuditorAware<String> auditorAware() {
return () -> Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.filter(Authentication::isAuthenticated)
.filter(a -> !(a instanceof AnonymousAuthenticationToken))
.map(Authentication::getName);
}
// In a request by user "ana" -> Optional["ana"]
// In a scheduled job, no login -> Optional.empty(), createdBy stays null

For batch jobs and message consumers, where no user is logged in, decide what should be recorded. A common choice is to return a system name such as Optional.of("system:billing-job") when there is no authentication, so audit fields never stay null. If T were a User entity instead of a String, the createdBy field would be a @ManyToOne to User.

5Seeing It Work

Here is what happens on insert and update. The service code never touches the audit fields.

Java
@Transactional
Customer create(String name) { return customers.save(new Customer(name)); }
// insert into customer (created_at, created_by, name, updated_at, updated_by, id)
// values ('2026-11-05T09:00:00Z', 'ana', 'Acme', '2026-11-05T09:00:00Z', 'ana', 1)
@Transactional
void rename(long id, String name) { customers.findById(id).orElseThrow().setName(name); }
// later, by user "ben":
// update customer set name = 'Acme Ltd', updated_at = '2026-11-06T14:30:00Z', updated_by = 'ben'
// where id = 1
Step throughAuditing during an update
ServiceHibernateAuditingEntityListenerAuditorAwareDatabase
change name on managed Customer
flush: dirty entity found
@PreUpdate callback
getCurrentAuditor()
"ben"
set updatedAt = now, updatedBy = ben
update customer set name, updated_at, updated_by

7 messages in order. Play them, or step through them one at a time.

The listener runs inside Hibernate's lifecycle, just before the SQL is written.

Notice that rename never calls save. The entity is managed, Hibernate detects the change at flush, the @PreUpdate callback runs, and the listener sets updatedAt and updatedBy before the update is written. On insert, both created and modified fields get the same values; setting modifyOnCreate = false on @EnableJpaAuditing leaves the modified fields null on insert instead.

6What Bypasses Auditing

Because auditing is a lifecycle callback, it only runs for entities that pass through Hibernate's insert and update of managed objects. A bulk JPQL update, @Modifying @Query("update Customer c set c.status = :s where ..."), changes rows directly in the database without loading entities, so no callback runs and updated_at stays old. Native SQL queries, scripts run by a DBA and writes from other applications bypass it for the same reason.

For bulk updates, set the fields in the query itself, set c.updatedAt = :now, c.updatedBy = :user, or rely on a database default or trigger for updated_at. If the business needs a full change history rather than just the last change, auditing columns are the wrong tool; Hibernate Envers or change data capture are designed for that.

Java
@Modifying
@Query("update Customer c set c.status = :s, c.updatedAt = :now, c.updatedBy = :by where c.region = :r")
int setStatus(@Param("s") Status s, @Param("r") String r,
@Param("now") Instant now, @Param("by") String by);
// without the extra fields, updated_at and updated_by would not change

7Follow-up questions

Can auditing use a custom clock, for example in tests?

Yes. @EnableJpaAuditing has a dateTimeProviderRef attribute that names a DateTimeProvider bean. Backing it with a java.time.Clock lets tests fix the time and assert exact values.

Does auditing work with Spring Data JDBC or MongoDB?

Yes, with their own enable annotations, @EnableJdbcAuditing and @EnableMongoAuditing. The field annotations and AuditorAware are shared across Spring Data modules; only the mechanism that calls them differs.

Can I audit without a base class?

Yes. Put @EntityListeners(AuditingEntityListener.class) and the annotated fields on each entity, or embed them. The base class only avoids repetition, and it keeps the column names consistent across tables.

8Conclusion

In this answer, we saw that Spring Data auditing is a JPA entity listener that fills @CreatedDate, @LastModifiedDate, @CreatedBy and @LastModifiedBy just before inserts and updates. We enabled it with @EnableJpaAuditing on its own configuration class, put the fields and the listener in a @MappedSuperclass, and supplied the user with an AuditorAware bean reading the SecurityContext. Because it runs in Hibernate's lifecycle, bulk updates and native SQL bypass it and must set the fields themselves.

What to say in the interviewAbout 100 seconds aloud

Open with

There are four pieces. First, I enable auditing with @EnableJpaAuditing on a configuration class, a separate one rather than the main application class, so test slices do not trip over it.

Then, if they want more

Second, the entity needs the listener: @EntityListeners(AuditingEntityListener.class). Third, the fields are annotated @CreatedDate, @LastModifiedDate, @CreatedBy and @LastModifiedBy. Since most entities need them, I put them in an abstract @MappedSuperclass with the listener on it, and mark the created columns updatable = false.

Fourth, for the user fields, I provide an AuditorAware<String> bean whose getCurrentAuditor reads the SecurityContext, returns the authentication name when the user is authenticated and not anonymous, and for jobs without a user returns something like a system name, so the fields are never null. With that in place, the service code never touches the fields.

On insert, the listener's pre-persist callback sets all four, and on update, when Hibernate finds a dirty managed entity at flush, the pre-update callback sets the modified date and user before the SQL is written. The important limitation is that this is all inside Hibernate's entity lifecycle.

A bulk JPQL update with @Modifying, a native query, or a script run directly on the database never loads entities, so no callback runs and updated_at stays stale. For those I set the fields explicitly in the query or use a database default.

And if someone needs full history rather than the last change, I would point them to Envers or change data capture.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Set up Spring Data JPA auditing so entities get createdAt, updatedAt and createdBy...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/1fed7e7a43/