Spring Data JPA auditing: who changed what, and when

Auditing fills in creation and modification dates and users on every save, without any code in your services. It is implemented as a JPA entity listener, and most auditing bugs come from the limits of that listener. This page shows auditing running with a fixed clock and real users, then the cases where the fields stay null or are wiped, and a full change history with Hibernate Envers.

Contents

How auditing works

Many tables need four extra columns: when a row was created, who created it, when it was last changed, and who changed it. Setting them by hand in every service method is repetitive and easy to forget. Spring Data JPA auditing sets them automatically, from annotations on the entity's fields.

The mechanism is a JPA entity listener. JPA lets an entity name listener classes with @EntityListeners, and calls their methods at points in the entity lifecycle. Spring Data's AuditingEntityListener handles two of them:

  • Before an insert (@PrePersist): it sets the created and the modified fields.
  • Before an update (@PreUpdate): it sets only the modified fields.

The listener gets the current time from a DateTimeProvider (the system clock by default) and the current user from an AuditorAware bean that you write. @EnableJpaAuditing switches the whole thing on. Because it is a listener, auditing runs only when Hibernate inserts or updates an entity. Anything that changes rows without going through an entity, such as a bulk UPDATE query or plain JDBC, is not audited.

Auditing annotations, from org.springframework.data.annotation
AnnotationSet onValue comes from
@CreatedDateInsertDateTimeProvider
@LastModifiedDateInsert and updateDateTimeProvider
@CreatedByInsertAuditorAware
@LastModifiedByInsert and updateAuditorAware

The date fields can be Instant, LocalDateTime, OffsetDateTime, the old Date and Calendar, or a long of epoch milliseconds. The user fields can be any type your AuditorAware returns: a user name, an id, or a user entity.

The alternatives are worth knowing too: Hibernate's own @CreationTimestamp and @UpdateTimestamp, plain JPA callbacks, Hibernate Envers for a full history, and database triggers. They are compared at the end. The examples use Spring Boot 4.1, Spring Data JPA 4.1 and Hibernate 7.4 on H2. To make the output repeatable, most of them use a fixed clock instead of the system time.

Turning auditing on

An invoice is created by alice, changed by bob a day later, then saved again by carol without any change. A DateTimeProvider bean returns a time the program sets, so the dates in the output are fixed. The static fields stand in for a real clock and a real login:

Java
package audit.basics;

import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Version;
import java.time.Instant;
import java.time.temporal.TemporalAccessor;
import java.util.Map;
import java.util.Optional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
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.auditing.DateTimeProvider;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
@EnableJpaAuditing(dateTimeProviderRef = "clock")
public class AuditingBasics {

    static String currentUser = "alice";
    static Instant now = Instant.parse("2026-01-05T09:00:00Z");

    @Bean
    AuditorAware<String> auditor() {
        return () -> Optional.of(currentUser);
    }

    @Bean
    DateTimeProvider clock() {
        return () -> Optional.<TemporalAccessor>of(now);
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(AuditingBasics.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            InvoiceRepository invoices = context.getBean(InvoiceRepository.class);

            Invoice invoice = invoices.save(new Invoice("INV-1", 100));
            System.out.println("Created : " + invoice);

            currentUser = "bob";
            now = Instant.parse("2026-01-06T14:30:00Z");
            invoice.setAmount(120);
            invoice = invoices.save(invoice);
            System.out.println("Updated : " + invoice);

            currentUser = "carol";
            now = Instant.parse("2026-01-07T08:15:00Z");
            invoice = invoices.save(invoice);
            System.out.println("Saved again with no change: " + invoice);
            System.out.println("In database: " + invoices.findById(invoice.getId()).orElseThrow());
        }
    }
}

@Entity
@EntityListeners(AuditingEntityListener.class)
class Invoice {
    @Id
    @GeneratedValue
    private Long id;
    private String number;
    private int amount;
    @Version
    private int version;

    @CreatedBy
    private String createdBy;
    @CreatedDate
    private Instant createdAt;
    @LastModifiedBy
    private String modifiedBy;
    @LastModifiedDate
    private Instant modifiedAt;

    protected Invoice() {
    }

    Invoice(String number, int amount) {
        this.number = number;
        this.amount = amount;
    }

    Long getId() {
        return id;
    }

    void setAmount(int amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return number + " amount=" + amount + " v" + version + " created " + createdBy + " "
                + createdAt + ", modified " + modifiedBy + " " + modifiedAt;
    }
}

interface InvoiceRepository extends JpaRepository<Invoice, Long> {
}
Output
Created : INV-1 amount=100 v0 created alice 2026-01-05T09:00:00Z, modified alice 2026-01-05T09:00:00Z
Updated : INV-1 amount=120 v1 created alice 2026-01-05T09:00:00Z, modified bob 2026-01-06T14:30:00Z
Saved again with no change: INV-1 amount=120 v1 created alice 2026-01-05T09:00:00Z, modified bob 2026-01-06T14:30:00Z
In database: INV-1 amount=120 v1 created alice 2026-01-05T09:00:00Z, modified bob 2026-01-06T14:30:00Z
  • On creation, all four fields were filled. The modified fields got the same values as the created ones, alice at 09:00 on 5 January. That is the default; @EnableJpaAuditing(modifyOnCreate = false) leaves the modified fields null until the first update.
  • bob's change set the modified fields to bob and 6 January, and left the created fields alone. The @Version field went from 0 to 1.
  • carol's save changed nothing, so Hibernate's dirty check found no difference, ran no UPDATE, and the listener never ran. The row still says bob, and the version is still 1. Auditing records real changes, not calls to save().

Three pieces are needed, and leaving out any one of them silently disables auditing for that entity: @EnableJpaAuditing on a configuration class, @EntityListeners(AuditingEntityListener.class) on the entity, and the annotations on its fields. dateTimeProviderRef names the clock bean; without it, the current system time is used. When there is exactly one AuditorAware bean, it is found automatically; with several, name one with auditorAwareRef.

The current user from Spring Security

In a real application, the user comes from the login. Spring Security keeps the current Authentication in the SecurityContextHolder, bound to the request's thread, so an AuditorAware can read it directly. The program saves three documents: with nobody logged in, as the anonymous user Spring Security uses for public pages, and as dana:

Java
package audit.security;

import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Map;
import java.util.Optional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

@SpringBootApplication
@EnableJpaAuditing
public class SecurityAuditor {

    @Bean
    AuditorAware<String> auditor() {
        return () -> Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .filter(Authentication::isAuthenticated)
                .filter(auth -> !(auth instanceof AnonymousAuthenticationToken))
                .map(Authentication::getName);
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(SecurityAuditor.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            DocumentRepository documents = context.getBean(DocumentRepository.class);

            System.out.println("No one logged in : " + documents.save(new Document("a.txt")));

            SecurityContextHolder.getContext().setAuthentication(
                    new AnonymousAuthenticationToken("key", "anonymousUser",
                            AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
            System.out.println("Anonymous user   : " + documents.save(new Document("b.txt")));

            SecurityContextHolder.getContext().setAuthentication(
                    UsernamePasswordAuthenticationToken.authenticated("dana", null,
                            AuthorityUtils.createAuthorityList("ROLE_USER")));
            System.out.println("Logged in as dana: " + documents.save(new Document("c.txt")));
            SecurityContextHolder.clearContext();
        }
    }
}

@Entity
@EntityListeners(AuditingEntityListener.class)
class Document {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @CreatedBy
    private String createdBy;
    @LastModifiedBy
    private String modifiedBy;

    protected Document() {
    }

    Document(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name + " createdBy=" + createdBy + " modifiedBy=" + modifiedBy;
    }
}

interface DocumentRepository extends JpaRepository<Document, Long> {
}
Output
No one logged in : a.txt createdBy=null modifiedBy=null
Anonymous user   : b.txt createdBy=null modifiedBy=null
Logged in as dana: c.txt createdBy=dana modifiedBy=dana
  • With no Authentication at all, the Optional was empty, and the user fields were left null.
  • The AnonymousAuthenticationToken counts as authenticated, so without the second filter the column would say anonymousUser. Filtering it out kept the column null.
  • Logged in as dana, both user fields got dana, the value of Authentication.getName().

Because the security context is bound to a thread, work done in @Async methods, scheduled jobs or message listeners has no user unless you pass one along. Those saves get null, or a fixed system user if your AuditorAware falls back to one. Returning a user id instead of a name keeps the column stable when people change their user names.

One base class for every entity

Repeating four fields and an @EntityListeners annotation on every entity is the kind of copying auditing was meant to avoid. A @MappedSuperclass holds them once; its fields become columns of each entity table that extends it. The second save here runs with no user set:

Java
package audit.base;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import java.time.Instant;
import java.time.temporal.TemporalAccessor;
import java.util.Map;
import java.util.Optional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
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.auditing.DateTimeProvider;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
@EnableJpaAuditing(dateTimeProviderRef = "clock")
public class BaseClassAuditing {

    static final ThreadLocal<String> CURRENT_USER = new ThreadLocal<>();

    @Bean
    AuditorAware<String> auditor() {
        return () -> Optional.ofNullable(CURRENT_USER.get());
    }

    @Bean
    DateTimeProvider clock() {
        return () -> Optional.<TemporalAccessor>of(Instant.parse("2026-03-01T12:00:00Z"));
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(BaseClassAuditing.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            CustomerRepository customers = context.getBean(CustomerRepository.class);
            OrderRepository orders = context.getBean(OrderRepository.class);

            CURRENT_USER.set("alice");
            System.out.println(customers.save(new Customer("Acme Ltd")));
            CURRENT_USER.remove();
            System.out.println(orders.save(new PurchaseOrder("PO-7")));
        }
    }
}

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
abstract class Auditable {
    @CreatedBy
    @Column(updatable = false)
    protected String createdBy;
    @CreatedDate
    @Column(updatable = false)
    protected Instant createdAt;
    @LastModifiedBy
    protected String modifiedBy;
    @LastModifiedDate
    protected Instant modifiedAt;

    protected String audit() {
        return " (created by " + createdBy + " at " + createdAt + ")";
    }
}

@Entity
class Customer extends Auditable {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    protected Customer() {
    }

    Customer(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Customer " + name + audit();
    }
}

@Entity
class PurchaseOrder extends Auditable {
    @Id
    @GeneratedValue
    private Long id;
    private String number;

    protected PurchaseOrder() {
    }

    PurchaseOrder(String number) {
        this.number = number;
    }

    @Override
    public String toString() {
        return "Order " + number + audit();
    }
}

interface CustomerRepository extends JpaRepository<Customer, Long> {
}

interface OrderRepository extends JpaRepository<PurchaseOrder, Long> {
}
Output
Customer Acme Ltd (created by alice at 2026-03-01T12:00:00Z)
Order PO-7 (created by null at 2026-03-01T12:00:00Z)
  • Both Customer and PurchaseOrder got the audit columns, and both were audited, although neither entity declares a listener: the @EntityListeners annotation on the superclass applies to its subclasses.
  • The order was saved after CURRENT_USER.remove(), so AuditorAware returned an empty Optional and createdBy is null. The date was still set, because dates and users are filled independently.
  • The ThreadLocal plays the part of the security context from the previous example.

Spring Data also ships AbstractAuditable, a ready-made base class, but it expects the user to be an entity (a @ManyToOne to your user table) and uses LocalDateTime. A small class of your own, as above, is usually a better fit. Mark the created columns @Column(updatable = false); the next section shows why.

Traps that leave audit fields wrong

Each of these three cases saves data successfully, and each leaves an audit field null or stale. The clock starts at 5 January and moves to 6 January before the updates:

Java
package audit.traps;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.time.Instant;
import java.time.temporal.TemporalAccessor;
import java.util.Map;
import java.util.Optional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

@SpringBootApplication
@EnableJpaAuditing(dateTimeProviderRef = "clock")
public class AuditingTraps {

    static Instant now = Instant.parse("2026-01-05T09:00:00Z");

    @Bean
    DateTimeProvider clock() {
        return () -> Optional.<TemporalAccessor>of(now);
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(AuditingTraps.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            NoteRepository notes = context.getBean(NoteRepository.class);
            TagRepository tags = context.getBean(TagRepository.class);
            ArticleRepository articles = context.getBean(ArticleRepository.class);

            System.out.println("1. Entity without @EntityListeners");
            System.out.println("   " + tags.save(new Tag("java")));

            System.out.println("2. Bulk update with @Modifying @Query");
            Note note = notes.save(new Note("draft"));
            Article article = articles.save(new Article("v1"));
            now = Instant.parse("2026-01-06T10:00:00Z");
            notes.renameAll("final");
            System.out.println("   " + notes.findById(note.getId()).orElseThrow());

            System.out.println("3. Saving a new object that carries an existing id");
            Note sameId = new Note("edited");
            sameId.setId(note.getId());
            notes.save(sameId);
            Article articleCopy = new Article("v2");
            articleCopy.setId(article.getId());
            articles.save(articleCopy);
            System.out.println("   Note (plain column)      : "
                    + notes.findById(note.getId()).orElseThrow());
            System.out.println("   Article (updatable=false): "
                    + articles.findById(article.getId()).orElseThrow());
        }
    }
}

@Entity
class Tag {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @CreatedDate
    private Instant createdAt;

    protected Tag() {
    }

    Tag(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name + " createdAt=" + createdAt;
    }
}

@Entity
@EntityListeners(AuditingEntityListener.class)
class Note {
    @Id
    @GeneratedValue
    private Long id;
    private String text;
    @CreatedDate
    private Instant createdAt;
    @LastModifiedDate
    private Instant modifiedAt;

    protected Note() {
    }

    Note(String text) {
        this.text = text;
    }

    Long getId() {
        return id;
    }

    void setId(Long id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return text + " createdAt=" + createdAt + " modifiedAt=" + modifiedAt;
    }
}

@Entity
@EntityListeners(AuditingEntityListener.class)
class Article {
    @Id
    @GeneratedValue
    private Long id;
    private String text;
    @CreatedDate
    @Column(updatable = false)
    private Instant createdAt;
    @LastModifiedDate
    private Instant modifiedAt;

    protected Article() {
    }

    Article(String text) {
        this.text = text;
    }

    Long getId() {
        return id;
    }

    void setId(Long id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return text + " createdAt=" + createdAt + " modifiedAt=" + modifiedAt;
    }
}

interface TagRepository extends JpaRepository<Tag, Long> {
}

interface NoteRepository extends JpaRepository<Note, Long> {
    @Modifying
    @Transactional
    @Query("update Note n set n.text = :text")
    int renameAll(@Param("text") String text);
}

interface ArticleRepository extends JpaRepository<Article, Long> {
}
Output
1. Entity without @EntityListeners
   java createdAt=null
2. Bulk update with @Modifying @Query
   final createdAt=2026-01-05T09:00:00Z modifiedAt=2026-01-05T09:00:00Z
3. Saving a new object that carries an existing id
   Note (plain column)      : edited createdAt=null modifiedAt=2026-01-06T10:00:00Z
   Article (updatable=false): v2 createdAt=2026-01-05T09:00:00Z modifiedAt=2026-01-06T10:00:00Z
  • Case 1: Tag has @CreatedDate but no @EntityListeners, so nothing filled it. There is no error or warning; the column is simply null.
  • Case 2: the bulk update Note n set n.text = :text changed the text to "final", but modifiedAt still says 5 January. The query ran in the database without loading entities, so @PreUpdate never fired. Set the audit columns in the query itself if a bulk update must be audited.
  • Case 3: a new Note object carrying an existing id, as a REST controller often builds from a request, was saved. save() merged it, copying every field, including the null createdAt, onto the stored row. The creation date was wiped. The Article entity has the same code, but its createdAt column is updatable = false, so Hibernate left it out of the UPDATE and the 5 January date survived.

Case 3 is the most common auditing bug in REST services. Besides updatable = false, the cleaner fix is to load the entity, copy the allowed fields from the request onto it, and let dirty checking write the change. The same reasoning applies to @CreatedBy.

Hibernate timestamps and JPA callbacks

When you only need dates, not users, two other mechanisms work without Spring Data's auditing: Hibernate's @CreationTimestamp and @UpdateTimestamp, and plain JPA lifecycle methods annotated with @PrePersist and @PreUpdate. They use the real clock, so this program prints which fields are set rather than the times:

Java
package audit.hibernate;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import java.time.Instant;
import java.util.Map;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class HibernateTimestamps {

    public static void main(String[] args) throws InterruptedException {
        SpringApplication app = new SpringApplication(HibernateTimestamps.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            TaskRepository tasks = context.getBean(TaskRepository.class);
            Task task = tasks.save(new Task("write report"));
            System.out.println("After insert: " + task.describe());
            Instant firstUpdated = task.updated;
            Thread.sleep(20);
            task.rename("write final report");
            task = tasks.save(task);
            System.out.println("After update: " + task.describe());
            System.out.println("@UpdateTimestamp moved forward: "
                    + task.updated.isAfter(firstUpdated));
        }
    }
}

@Entity
class Task {
    @Id
    @GeneratedValue
    private Long id;
    private String title;

    @CreationTimestamp
    private Instant created;
    @UpdateTimestamp
    Instant updated;

    private Instant callbackCreated;
    private Instant callbackUpdated;
    private int updates;

    protected Task() {
    }

    Task(String title) {
        this.title = title;
    }

    @PrePersist
    void onInsert() {
        callbackCreated = Instant.now();
    }

    @PreUpdate
    void onUpdate() {
        callbackUpdated = Instant.now();
        updates++;
    }

    void rename(String title) {
        this.title = title;
    }

    String describe() {
        return "@CreationTimestamp " + set(created) + ", @UpdateTimestamp " + set(updated)
                + ", @PrePersist " + set(callbackCreated) + ", @PreUpdate " + set(callbackUpdated)
                + ", updates=" + updates;
    }

    private static String set(Instant value) {
        return value == null ? "null" : "set";
    }
}

interface TaskRepository extends JpaRepository<Task, Long> {
}
Output
After insert: @CreationTimestamp set, @UpdateTimestamp set, @PrePersist set, @PreUpdate null, updates=0
After update: @CreationTimestamp set, @UpdateTimestamp set, @PrePersist set, @PreUpdate set, updates=1
@UpdateTimestamp moved forward: true
  • After the insert, both Hibernate timestamps were set, and the @PrePersist method had run. @UpdateTimestamp is set on insert too, like @LastModifiedDate with its default.
  • After the update, the @PreUpdate method had run once (updates=1), and the @UpdateTimestamp value had moved forward.
  • No @EnableJpaAuditing, listener class or bean was needed. The trade-offs: there is no "who", and the time always comes from the JVM clock, which makes tests that check exact times harder.

JPA callbacks are useful for other derived values as well, such as a normalized search column or a slug. They run under the same rule as auditing: only when Hibernate writes the entity itself.

Full change history with Hibernate Envers

Auditing columns keep only the latest change. When you need every version of a row, for example to show who changed a price and what it was before, Hibernate Envers records history tables. Add org.hibernate.orm:hibernate-envers, whose version Spring Boot manages (7.4.13 here, matching Hibernate ORM), and annotate the entity with @Audited. No other configuration is needed: Hibernate finds Envers on the classpath and registers its event listeners.

This program creates a product as alice, changes it twice as bob, tries a change that is rolled back, and deletes it. A custom revision entity records who made each revision:

Java
package audit.envers;

import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.hibernate.envers.Audited;
import org.hibernate.envers.RevisionEntity;
import org.hibernate.envers.RevisionListener;
import org.hibernate.envers.RevisionNumber;
import org.hibernate.envers.RevisionTimestamp;
import org.hibernate.envers.RevisionType;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.support.TransactionTemplate;

@SpringBootApplication
public class EnversHistory {

    static void as(String user) {
        SecurityContextHolder.getContext().setAuthentication(
                UsernamePasswordAuthenticationToken.authenticated(user, null,
                        AuthorityUtils.NO_AUTHORITIES));
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(EnversHistory.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            TransactionTemplate tx = context.getBean(TransactionTemplate.class);
            EntityManager em = context.getBean(EntityManager.class);

            as("alice");
            long id = tx.execute(s -> {
                Product p = new Product("Desk lamp", new BigDecimal("10.00"));
                em.persist(p);
                return p.id;
            });
            as("bob");
            tx.executeWithoutResult(s -> em.find(Product.class, id).price = new BigDecimal("12"));
            tx.executeWithoutResult(s -> {                    // two changes, one transaction
                Product p = em.find(Product.class, id);
                p.price = new BigDecimal("11.00");
                em.flush();
                p.name = "Desk lamp LED";
            });
            try {
                tx.executeWithoutResult(s -> {
                    em.find(Product.class, id).price = BigDecimal.ONE;
                    throw new IllegalStateException("payment check failed");
                });
            } catch (IllegalStateException e) {
                System.out.println("Rolled back: " + e.getMessage());
            }
            as("alice");
            tx.executeWithoutResult(s -> em.remove(em.find(Product.class, id)));

            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("product rows now: "
                    + jdbc.queryForObject("select count(*) from product", Integer.class));
            System.out.println("product_aud (id, rev, revtype, name, price):");
            jdbc.queryForList("select id, rev, revtype, name, price from product_aud"
                            + " order by rev")
                    .forEach(row -> System.out.println("  " + row.values()));
            System.out.println("revinfo (id, username):");
            jdbc.queryForList("select id, username from revinfo order by id")
                    .forEach(row -> System.out.println("  " + row.values()));

            tx.executeWithoutResult(s -> {
                AuditReader reader = AuditReaderFactory.get(em);
                List<Number> revisions = reader.getRevisions(Product.class, id);
                System.out.println("getRevisions -> " + revisions);
                Product atRev2 = reader.find(Product.class, id, revisions.get(1));
                System.out.println("find at revision " + revisions.get(1) + " -> "
                        + atRev2.name + " " + atRev2.price);
                @SuppressWarnings("unchecked")
                List<Object[]> history = reader.createQuery()
                        .forRevisionsOfEntity(Product.class, false, true)
                        .getResultList();
                for (Object[] row : history) {
                    Product p = (Product) row[0];
                    Revision rev = (Revision) row[1];
                    RevisionType type = (RevisionType) row[2];
                    System.out.println("  rev " + rev.getId() + " " + type + " by "
                            + rev.getUsername() + ": " + p.name + " " + p.price);
                }
            });
        }
    }
}

@Entity
@Audited
class Product {
    @Id
    @GeneratedValue
    Long id;
    String name;
    BigDecimal price;

    protected Product() {
    }

    Product(String name, BigDecimal price) {
        this.name = name;
        this.price = price;
    }
}

@Entity
@Table(name = "revinfo")
@RevisionEntity(UserRevisionListener.class)
class Revision {
    @Id
    @GeneratedValue
    @RevisionNumber
    int id;

    @RevisionTimestamp
    long timestamp;

    String username;

    // Envers may return a lazy proxy: read it through methods, never through its fields
    int getId() {
        return id;
    }

    String getUsername() {
        return username;
    }
}

class UserRevisionListener implements RevisionListener {
    @Override
    public void newRevision(Object revisionEntity) {
        var auth = SecurityContextHolder.getContext().getAuthentication();
        ((Revision) revisionEntity).username = auth == null ? "system" : auth.getName();
    }
}
Output
Rolled back: payment check failed
product rows now: 0
product_aud (id, rev, revtype, name, price):
  [1, 1, 0, Desk lamp, 10.00]
  [1, 2, 1, Desk lamp, 12.00]
  [1, 3, 1, Desk lamp LED, 11.00]
  [1, 4, 2, null, null]
revinfo (id, username):
  [1, alice]
  [2, bob]
  [3, bob]
  [4, alice]
getRevisions -> [1, 2, 3, 4]
find at revision 2 -> Desk lamp 12.00
  rev 1 ADD by alice: Desk lamp 10.00
  rev 2 MOD by bob: Desk lamp 12.00
  rev 3 MOD by bob: Desk lamp LED 11.00
  rev 4 DEL by alice: null null
  • product_aud got one row per transaction that changed the product: revision 1 with revtype 0 (add), revisions 2 and 3 with 1 (modify), and revision 4 with 2 (delete). The product table itself was empty at the end; the history outlives the row.
  • The third transaction changed the price, flushed, then changed the name, and still produced one revision, 3, with the final state Desk lamp LED 11.00. Envers records per transaction, not per statement.
  • The rolled-back change to price 1 left no trace: Envers writes in the same transaction as the change, so a rollback removes the history row with it.
  • The delete row holds null for every field. By default Envers stores only the id of a deleted entity; set org.hibernate.envers.store_data_at_delete=true (as a spring.jpa.properties.* property) to keep its last values.
  • revinfo names the user of each revision, filled in by UserRevisionListener from the Spring Security context. Envers calls the listener once per revision, when it creates the revision entity.
  • getRevisions listed the revision numbers 1 to 4, and find at revision 2 rebuilt the product as it was then, with price 12.00. forRevisionsOfEntity(Product.class, false, true) returned each version together with its revision entity and type, including the deletion.

The revision entity is read through methods, as the comment in it says. With the loop reading rev.id and rev.username as fields instead, revision 2 printed as rev 0 MOD by null: Envers had returned an uninitialized Hibernate proxy, whose own fields keep their default values. Calling a method loads the proxy.

The spring-data-envers module adds RevisionRepository, whose findRevisions(id) and findLastChangeRevision(id) wrap the same AuditReader queries for repositories; it was not used here. The cost of Envers is an extra insert per changed entity per transaction, plus one revinfo row, and history tables that grow without limit unless you archive them.

Testing audited entities

  • Fix the clock: a DateTimeProvider bean that returns a value the test controls, as on this page, lets a test assert exact dates. In production, back it with an injected java.time.Clock, and replace that bean in tests.
  • Set the user: with Spring Security, @WithMockUser(username = "dana") from spring-security-test fills the security context for a test method.
  • Flush before you check: the listener runs when Hibernate writes. In a test that does not commit, call saveAndFlush or flush() before reading the fields of an update.
  • Use @DataJpaTest: it starts only the JPA part of the application, but @EnableJpaAuditing on the main application class is still applied. If you put it on a separate configuration class instead, import that class in the test.

Choosing an auditing approach

Ways to record when and by whom data changed
ApproachRecordsBest for
Spring Data auditingLatest create and change time and userMost applications; testable with a fixed clock
@CreationTimestamp, @UpdateTimestampLatest times onlySimple timestamps without any setup
JPA @PrePersist, @PreUpdateWhatever the method setsDerived values, or auditing without Spring Data
Hibernate EnversEvery version of every rowRegulated data and "show the history" features
Database triggersAnything, for every clientTables also written by scripts or other applications

Whichever you choose, remember that the first four only see changes made through JPA entities. The Spring Data JPA page explains save(), merging and dirty checking, which decide when the listener runs. Auditing combines well with soft delete, where a deletion becomes an audited update, and Spring Security supplies the user.