Skip to main content

JPA Auditing in Spring Boot 4: @CreatedDate, @LastModifiedBy and the Current User

Spring Data JPA auditing on Spring Boot 4.1: the four annotations, an AuditorAware that does not store “anonymousUser”, Instant vs LocalDateTime across time zones, the four ways auditing silently does nothing, and Envers history, all verified with real output.

You add a createdAt and a createdBy column to a table, and two weeks later someone asks who changed a price and when. You can answer only if every code path that writes the row remembered to fill those columns. Spring Data JPA auditing exists so that no code path has to remember: you annotate four fields once, and every save() fills them. It works well, and it also fails silently in several ways: a missing annotation, a bulk update, a request with no login, another thread. Each of those leaves you with null or wrong values and no exception. This post builds the working version first, then breaks it on purpose in each of those ways and shows what the symptom looks like. Every number and every line of output below came from a test that was compiled and run, and each test also asserts what it prints.
Versions tested (checked against Maven Central metadata on 2026-11-17). Spring Boot 4.1.2, Spring Data JPA 4.1.2, Spring Framework 7.0.10, Spring Security 7.1.2, Hibernate ORM and Envers 7.4.13.Final, H2 2.4.240, Temurin JDK 25.0.5 LTS. The companion module is spring-data-demo/jpa-auditing and every transcript quoted here is in its output/ folder. There is no separate docs folder: the deeper material is in the expandable “Going deeper” sections on this page.

Auditing is four annotations, one switch and one listener

Auditing means recording, on each row, when it was created, when it last changed, who created it and who last changed it. Spring Data does this by hooking into the moment JPA is about to write the row. Three separate pieces cooperate, and the whole topic is easier once you can name them:
  • The field annotations — @CreatedDate, @LastModifiedDate, @CreatedBy, @LastModifiedBy — mark which fields get filled.
  • The listener — @EntityListeners(AuditingEntityListener.class) on the entity — tells JPA to call Spring Data just before an insert or update.
  • The switch — @EnableJpaAuditing on a configuration class — creates the object that does the filling.
repo.save(a)your codeJPA callback@PrePersist /@PreUpdateAuditingEntityListenernamed by @EntityListenersAuditingHandlerasks DateTimeProvider (when)asks AuditorAware (who)createdAt updatedAt createdBy updatedByRemove any link in this chain and the columns stay null, with no error.@EnableJpaAuditing creates the AuditingHandler; @EntityListeners hooks the entity to it.The four annotations on the fields only say WHAT to fill. They do nothing on their own.
The diagram shows the chain. When you call save(), Hibernate fires a JPA callback, which reaches AuditingEntityListener, which asks an AuditingHandler for the current time and the current user and writes both into the entity before the SQL goes out. The thing to take from it: the annotations on the fields are only labels. If either the listener or the switch is missing, nothing fills them, and a later section shows exactly what that looks like.
Going deeper: why Spring Data uses a JPA entity listener The listener is an ordinary JPA mechanism (@PrePersist and @PreUpdate callbacks), not something Hibernate-specific, so auditing works the same on any JPA provider. The cost is that it only sees changes made through the persistence context. Anything that goes straight to SQL, such as a bulk update, never reaches the callback; the “When auditing silently does nothing” section below shows that with real SQL.

The smallest setup that works

Put the four fields in a base class so every entity inherits them. The first block is the whole base class (from Auditable.java), with the getters left out:
@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;
updatable = false on the creation columns is a safety net: even if someone later calls a setter or merges a detached copy, Hibernate will not include those columns in an UPDATE. Then the switch, from AuditingConfig.java. The two Ref attributes point at beans that supply the user and the clock; the next two sections explain both.
@EnableJpaAuditing(auditorAwareRef = "auditorAware", dateTimeProviderRef = "dateTimeProvider")
public class AuditingConfig {
An entity now only has to extend the base class. Here is one create and one update from the test CreateUpdateTest.java, where alice creates an article and bob edits it two hours later. The transcript is output/01-create-update.txt:
# create as alice at 2026-11-17T08:00:00Z
createdAt=2026-11-17T08:00:00Z updatedAt=2026-11-17T08:00:00Z
createdBy=alice updatedBy=alice

# update as bob at 2026-11-17T10:00:00Z
createdAt=2026-11-17T08:00:00Z updatedAt=2026-11-17T10:00:00Z
createdBy=alice updatedBy=bob
UPDATE SQL: update article set body=?,title=?,updated_at=?,updated_by=? where id=?
Three things are visible here. updatedAt equals createdAt on creation, because a brand-new row counts as modified. After bob’s edit, updatedAt and updatedBy move but createdAt and createdBy do not. And the UPDATE statement does not list the creation columns at all, which is the updatable = false from above doing its job.
Going deeper: the other options on @EnableJpaAuditing @EnableJpaAuditing has four attributes (I read them with javap on the 4.1.2 jar): auditorAwareRef, dateTimeProviderRef, setDates and modifyOnCreate. You only need the first two when more than one bean of that type exists, but naming them explicitly is clearer. modifyOnCreate defaults to true, which is the updatedAt == createdAt behaviour in the output above; set it to false if you want updatedAt to stay null until the first real edit. I did not run that variant, so treat it as documented behaviour rather than verified output. setDates = false keeps the who columns while turning off the when columns. The companion module replaces the default clock with a settable one (DemoClock in AuditingConfig.java) so that every timestamp in every transcript is the same on every run. In production you would normally leave dateTimeProviderRef out, or inject a Clock bean so your own tests can control time.
  • Add optimistic locking next to auditing with a @Version field. I kept that out of the repository to stay focused; the base class with it added is here: download AuditableWithVersion.java. It compiles against the same dependencies, and I did not run it as part of the test suite.
Inline code: AuditableWithVersion.java (a variant, not in the repository)
package com.ankurm.jpaauditing;

import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.Version;
import java.time.Instant;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

/**
 * Auditable plus optimistic locking. @Version is not part of auditing, but the two belong together:
 * auditing says who saved last, @Version stops two people silently overwriting each other.
 */
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AuditableWithVersion {

    @Version
    private long version;

    @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 long getVersion() { return version; }
    public Instant getCreatedAt() { return createdAt; }
    public Instant getUpdatedAt() { return updatedAt; }
    public String getCreatedBy() { return createdBy; }
    public String getUpdatedBy() { return updatedBy; }
}

Download AuditableWithVersion.java

Where does “who” come from? The AuditorAware bean

Spring Data knows the current time by itself, but it has no idea who the current user is. You tell it by providing an AuditorAware<T> bean whose single method returns the current user, or an empty Optional if there is none. With Spring Security the answer is in the SecurityContext. A common way to write it is the next version, and it has a bug:
public class NaiveAuditorAware implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .map(Authentication::getName);
    }
}
The bug is not in the code you can see. A request with no login is not “no authentication” in Spring Security: a filter fills the context with an anonymous token whose name is the literal string anonymousUser. The naive version stores that string. This is NaiveAuditorTest.java, a real POST with no credentials, transcript output/06-naive-auditor-anonymous.txt:
# demo.auditor=naive, POST /articles with NO credentials
{"id":1,"title":"From REST","createdBy":"anonymousUser","updatedBy":"anonymousUser","createdAt":"2026-11-17T08:00:00Z","updatedAt":"2026-11-17T08:00:00Z"}
Logged in as aliceAuthentication.getName() = aliceNo login (anonymous)AnonymousAuthenticationTokengetName() = anonymousUserBoth auditorsreturn “alice”NaiveAuditorAwarereturns “anonymousUser”SecurityContextAuditorAwarereturns Optional.empty()created_by = anonymousUsercreated_by = NULLA literal “anonymousUser” in a column looks like a real person in every report. NULL is honest.
The diagram compares the two paths. A logged-in user gives the same answer from either auditor. The difference is only for anonymous requests: the naive auditor writes a fake user name into the column, while the safe one returns an empty Optional, which tells Spring Data to leave the field alone, so a new row gets NULL. Here is the safe version, from SecurityContextAuditorAware.java:
public class SecurityContextAuditorAware implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) {
            return Optional.empty();
        }
        return Optional.of(auth.getName());
    }
}
And the result over real HTTP Basic requests, from SafeAuditorTest.java, transcript output/07-safe-auditor-two-users.txt. Because the test clock is fixed, updatedAt does not change between alice’s create and bob’s edit here; what the transcript demonstrates is the who columns:
# demo.auditor=safe, POST /articles with NO credentials
{"id":1,"title":"From REST","createdBy":null,"updatedBy":null,"createdAt":"2026-11-17T08:00:00Z","updatedAt":"2026-11-17T08:00:00Z"}

# POST as alice (HTTP Basic)
{"id":2,"title":"From REST","createdBy":"alice","updatedBy":"alice","createdAt":"2026-11-17T08:00:00Z","updatedAt":"2026-11-17T08:00:00Z"}

# PUT as bob
{"id":2,"title":"Edited by bob","createdBy":"alice","updatedBy":"bob","createdAt":"2026-11-17T08:00:00Z","updatedAt":"2026-11-17T08:00:00Z"}
An empty Optional is not a value. For a new row, empty means the column is NULL. For an update, empty means “leave the existing updatedBy as it was” — I did not run that second case, so check it in your own tests before relying on it. If you would rather record a fixed actor such as system for scheduled jobs, see the going-deeper section below.
Going deeper: the user disappears on other threads The SecurityContext is stored per thread. Work you hand to an @Async method, an executor, or a CompletableFuture runs on a different thread, where the context is empty, so the safe auditor correctly reports “no user” and your rows get NULL. The test OtherThreadTest.java saves one row from a plain pool thread and one through Spring Security’s DelegatingSecurityContextExecutor. Transcript output/08-other-thread.txt:
# test method runs as alice
auditor on the request thread : Optional[alice]
auditor on a plain pool thread: Optional.empty
createdBy of row saved on a plain pool thread               : null
createdBy of row saved via DelegatingSecurityContextExecutor: alice
If you see created_by filled for web requests and NULL for rows created by background work, this is the cause. Wrap the executor so it carries the context along (as the test does), or decide that background work is “system”.
Going deeper: a fixed “system” actor instead of NULL Some teams want every row attributed to something, for example when created_by is NOT NULL or when nightly jobs should be visible in an audit report. The change is small: return Optional.of("system") instead of Optional.empty(). This class is not in the repository; I compiled it and ran a small check that an empty context yields system and a logged-in alice yields alice, then removed the check. Download SystemFallbackAuditorAware.java.
package com.ankurm.jpaauditing;

import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Variant of SecurityContextAuditorAware for batch jobs, schedulers and message listeners:
 * when there is no logged-in user, record a fixed "system" actor instead of leaving the
 * column NULL. Use this only if created_by is NOT NULL or you want jobs to be visible in reports.
 */
public class SystemFallbackAuditorAware implements AuditorAware<String> {

    public static final String SYSTEM = "system";

    @Override
    public Optional<String> getCurrentAuditor() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) {
            return Optional.of(SYSTEM);
        }
        return Optional.of(auth.getName());
    }
}
The trade-off: with a fixed actor you can no longer tell “a job did this” from “an unauthenticated request did this”, since both become system. NULL keeps that distinction.

Instant or LocalDateTime for the timestamps?

Spring Data can fill several date types; the two worth comparing are Instant and LocalDateTime, and the choice matters more than it looks. A LocalDateTime is a wall-clock reading with no time zone attached: “13:30” is meaningless until you know where. An Instant is a point on the timeline. The entity LocalStamp.java stores the same @CreatedDate both ways, and TimeTypesTest.java runs it in three JVMs that differ only in -Duser.timezone, with the clock fixed at 2026-11-17T08:00:00Z. The three transcripts are output/09-instant-vs-localdatetime-UTC.txt, output/09-instant-vs-localdatetime-Asia-Kolkata.txt and output/09-instant-vs-localdatetime-America-New_York.txt. Here is Asia/Kolkata:
JVM zone: Asia/Kolkata   (clock instant: 2026-11-17T08:00:00Z)
column CREATED_INSTANT : TIMESTAMP WITH TIME ZONE
column CREATED_LOCAL : TIMESTAMP
stored LocalDateTime : 2026-11-17T13:30
stored Instant       : 2026-11-17T08:00:00Z
JVM zoneLocalDateTime columnInstant columnUTC2026-11-17T08:002026-11-17T08:00:00ZAsia/Kolkata2026-11-17T13:302026-11-17T08:00:00ZAmerica/New_York2026-11-17T03:002026-11-17T08:00:00ZSame moment, three different local values. Only the Instant column says which moment it was.
The diagram puts the three runs side by side. The Instant column is the same moment everywhere, while the LocalDateTime column is 08:00, 13:30 or 03:00 depending on which server happened to run the code. If a service is ever moved between regions, or two services in different zones write to one table, the LocalDateTime values stop being comparable and nothing tells you so. Use Instant unless you have a specific reason not to.
What Hibernate 7 did with the types. On H2 the Instant column was created as TIMESTAMP WITH TIME ZONE and the LocalDateTime column as plain TIMESTAMP (shown in the transcript above). Other databases map these differently, so check the DDL on yours rather than assuming.
Going deeper: running the three zones yourself The zone is set through a Maven property, so you can try any zone with one command. The script is time-zones.sh:
./scripts/time-zones.sh
# or one zone:
mvn -q test -Dtest=TimeTypesTest -Dtest.tz=Europe/Berlin
Setting the zone with -Duser.timezone at JVM start is the realistic scenario (a server in another region). I first tried switching the default zone inside one JVM with TimeZone.setDefault and got the same local value for both zones, so the test uses separate JVM runs instead; I did not dig into why.

When auditing silently does nothing

This is the part that costs real time, because each of these fails without an error pointing at the cause. All four are reproduced in the companion module.

1. You forgot @EnableJpaAuditing

Without the switch, the auditing machinery is never registered, so the annotations do nothing. In AuditingNotEnabledTest.java the config is turned off. Because createdAt is declared nullable = false, the symptom here is a database-style error rather than a quiet null (transcript output/04-auditing-not-enabled.txt):
# demo.auditing.enabled=false  (i.e. no @EnableJpaAuditing)
AuditingConfig bean present: false
save() threw: org.springframework.dao.DataIntegrityViolationException
root cause: not-null property references a null or transient value for entity com.ankurm.jpaauditing.Article.createdAt
If your column is nullable you would see no error at all, just nulls, which is the next case.

2. The entity has no @EntityListeners

The switch is on, the field is annotated, and still nothing is filled, because this entity never told JPA to call the listener. The entity is ForgottenListener.java; the test is MissingListenerTest.java, transcript output/05-missing-entity-listener.txt:
# @EnableJpaAuditing is ON, but the entity has @CreatedDate and no @EntityListeners
saved id=1 createdAt=null
exception: none
The fingerprint: some entities have their audit columns filled and one does not, no exception anywhere. Compare the one that fails with one that works — the difference is almost always the missing @EntityListeners (or a base class that was not extended).

3. A save that changes nothing does not stamp anything

Auditing runs when Hibernate decides a row is dirty. If you load an entity, set a field to the value it already has, and save it, no UPDATE is issued and updatedAt stays put. That is usually what you want, but it surprises people who expect “saved at” semantics. From CreateUpdateTest.java, transcript output/02-no-change-no-stamp.txt:
# save an entity whose fields did not change, clock moved to 12:00Z
UPDATE statements issued: 0
updatedAt=2026-11-17T08:00:00Z (still the create time)

4. Bulk updates bypass auditing completely

A @Modifying JPQL update runs as one SQL statement against the table. No entity is loaded, so no callback fires and no audit column changes. From ArticleRepository.java and the same test class, transcript output/03-bulk-update-bypass.txt:
# @Modifying JPQL update at 09:30Z as alice
SQL: update article a1_0 set title=? where a1_0.id=?
title=Renamed (bulk) updatedAt=2026-11-17T08:00:00Z updatedBy=alice

# the same update, setting the audit columns in the query itself, at 09:45Z
title=Renamed (stamped) updatedAt=2026-11-17T09:45:00Z updatedBy=alice
The title changed and updatedAt did not, so a report that says “last modified 08:00” is now wrong. The fix is to set the audit columns yourself inside the query, as the second half of the transcript shows. This method is in ArticleRepository.java:
    /** The fix for the above: a bulk update has to set the audit columns itself. */
    @Transactional   // custom @Modifying methods are NOT transactional by default; flushAutomatically needs one
    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Query("update Article a set a.title = :title, a.updatedAt = :now, a.updatedBy = :by where a.id = :id")
    int renameBulkStamped(@Param("id") Long id, @Param("title") String title,
                          @Param("now") Instant now, @Param("by") String by);
Going deeper: why the bulk method needs @Transactional Spring Data’s built-in methods such as save() are already transactional. Methods you declare yourself with @Query and @Modifying are not, and flushAutomatically = true needs a transaction to flush in. The first version of my test failed with exactly this; I kept the failing method in the repository as renameBulkNoTx so the error is reproducible. Transcript output/11-modifying-needs-transaction.txt:
# @Modifying(flushAutomatically = true) method with no @Transactional, called from plain code
exception: org.springframework.dao.InvalidDataAccessApiUsageException
message  : No EntityManager with actual transaction available for current thread - cannot reliably process 'flush' call
Going deeper: making these failures testable Surefire is set to start a fresh JVM for each test class (reuseForks=false in pom.xml). The reason: when I first put the “auditing not enabled” check in the same JVM as tests that had already started a Spring context with auditing on, it did not throw, and passed on its own. I did not find the exact cause, so I did not build on it; separate JVMs made the result repeatable. If you write a test like this, run it alone as well as in the full suite.

Keeping history, not just the latest stamps: Envers

Auditing answers “who touched this last”. It cannot answer “what did it look like on Tuesday”, because each update overwrites the previous values. Hibernate Envers is the companion for that: it writes a copy of the row to a history table on every change. The two are complementary, and the Envers revision can record the user too. One entity needs the Envers annotation, and one small revision entity records the user. First the entity, from Document.java:
@Entity
@Audited(auditParents = Auditable.class)
public class Document extends Auditable {
Then the revision entity and its listener, which Envers calls once per revision. From AuditRevision.java and UsernameRevisionListener.java:
@Entity
@RevisionEntity(UsernameRevisionListener.class)
public class AuditRevision {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @RevisionNumber
    private Long id;

    @RevisionTimestamp
    private long timestamp;

    private String username;
public class UsernameRevisionListener implements RevisionListener {
    @Override
    public void newRevision(Object revisionEntity) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        ((AuditRevision) revisionEntity).setUsername(auth == null ? null : auth.getName());
    }
}
The test EnversHistoryTest.java has alice create a document, bob edit it, then alice edit it again. Transcript output/10-envers-history.txt:
# the row itself (Spring Data auditing): only the latest stamps
content=v3 createdBy=alice updatedBy=alice updatedAt=2026-11-17T10:00:00Z

# the history (Envers): one row per revision
rev 1  revision.username=alice content=v1 updatedBy=alice updatedAt=2026-11-17T08:00:00Z
rev 2  revision.username=bob   content=v2 updatedBy=bob   updatedAt=2026-11-17T09:00:00Z
rev 3  revision.username=alice content=v3 updatedBy=alice updatedAt=2026-11-17T10:00:00Z
The row itself holds only the latest stamps (content=v3, last touched by alice), while the history has all three versions with who made each one. I used auditParents = Auditable.class so the audit columns appear in the history rows too; the output shows updatedBy and updatedAt per revision.
Going deeper: what Envers does and does not give you Envers adds a history table and a revision table, which means extra writes per change, so write-heavy tables pay for it. I did not test whether bulk updates are captured, so check that before relying on it. I only exercised the Hibernate AuditReader API directly; there is also a Spring Data Envers module, but its latest version on Maven Central was a release candidate when I checked, so I did not use it.

Should you build it this way at all?

Usually yes for the four columns, no for a full audit trail. Spring Data auditing is cheap and worth having on almost every table: it costs four columns and no extra queries. But it is a statement about the latest change made through JPA. It will not record bulk updates, direct SQL, or other applications writing to the same table, and it keeps no history. If you need compliance-grade traceability (who changed what, from which value to which), use Envers or database-level triggers, and accept the write cost. If your users are mostly anonymous, decide deliberately between NULL and a fixed actor before you ship, because changing it later means rewriting data.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.