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 @EntityListenersAuditingEntityListener
- Before an insert (
): it sets the created and the modified fields.@PrePersist - Before an update (
): it sets only the modified fields.@PreUpdate
The listener gets the current time from a DateTimeProviderAuditorAware@EnableJpaAuditingUPDATE
| Annotation | Set on | Value comes from |
|---|---|---|
@CreatedDate | Insert | DateTimeProvider |
@LastModifiedDate | Insert and update | DateTimeProvider |
@CreatedBy | Insert | AuditorAware |
@LastModifiedBy | Insert and update | AuditorAware |
The date fields can be InstantLocalDateTimeOffsetDateTimeDateCalendarlongAuditorAware
The alternatives are worth knowing too: Hibernate's own @CreationTimestamp@UpdateTimestamp
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
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> {
}
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;
leaves the modified fields@EnableJpaAuditing(modifyOnCreate = false) until the first update.null - bob's change set the modified fields to bob and 6 January, and left the created fields alone. The
field went from 0 to 1.@Version - carol's save changed nothing, so Hibernate's dirty check found no difference, ran no
, and the listener never ran. The row still says bob, and the version is still 1. Auditing records real changes, not calls toUPDATE .save()
Three pieces are needed, and leaving out any one of them silently disables auditing for that entity: @EnableJpaAuditing@EntityListeners(AuditingEntityListener.class)dateTimeProviderRefAuditorAwareauditorAwareRef
The current user from Spring Security
In a real application, the user comes from the login. Spring Security keeps the current AuthenticationSecurityContextHolderAuditorAware
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> {
}
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
at all, theAuthentication was empty, and the user fields were leftOptional .null - The
counts as authenticated, so without the secondAnonymousAuthenticationToken the column would sayfilter . Filtering it out kept the columnanonymousUser .null - Logged in as dana, both user fields got
, the value ofdana .Authentication.getName()
Because the security context is bound to a thread, work done in @AsyncnullAuditorAware
One base class for every entity
Repeating four fields and an @EntityListeners@MappedSuperclass
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> {
}
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
andCustomer got the audit columns, and both were audited, although neither entity declares a listener: thePurchaseOrder annotation on the superclass applies to its subclasses.@EntityListeners - The order was saved after
, soCURRENT_USER.remove() returned an emptyAuditorAware andOptional iscreatedBy . The date was still set, because dates and users are filled independently.null - The
plays the part of the security context from the previous example.ThreadLocal
Spring Data also ships AbstractAuditable@ManyToOneLocalDateTime@Column(updatable = false)
Traps that leave audit fields wrong
Each of these three cases saves data successfully, and each leaves an audit field null
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> {
}
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:
hasTag but no@CreatedDate , so nothing filled it. There is no error or warning; the column is simply@EntityListeners .null - Case 2: the bulk
changed the text to "final", butupdate Note n set n.text = :text still says 5 January. The query ran in the database without loading entities, somodifiedAt never fired. Set the audit columns in the query itself if a bulk update must be audited.@PreUpdate - Case 3: a new
object carrying an existing id, as a REST controller often builds from a request, was saved.Note merged it, copying every field, including thesave()null , onto the stored row. The creation date was wiped. ThecreatedAt entity has the same code, but itsArticle column iscreatedAt , so Hibernate left it out of theupdatable = false and the 5 January date survived.UPDATE
Case 3 is the most common auditing bug in REST services. Besides updatable = false@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@UpdateTimestamp@PrePersist@PreUpdate
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> {
}
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
method had run.@PrePersist is set on insert too, like@UpdateTimestamp with its default.@LastModifiedDate - After the update, the
method had run once (@PreUpdate ), and theupdates=1 value had moved forward.@UpdateTimestamp - No
, 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.@EnableJpaAuditing
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@Audited
This program creates a product as alicebob
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();
}
}
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
got one row per transaction that changed the product: revision 1 withproduct_aud 0 (add), revisions 2 and 3 with 1 (modify), and revision 4 with 2 (delete). Therevtype table itself was empty at the end; the history outlives the row.product- The third transaction changed the price, flushed, then changed the name, and still produced one revision, 3, with the final state
. Envers records per transaction, not per statement.Desk lamp LED 11.00 - 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
for every field. By default Envers stores only the id of a deleted entity; setnull (as aorg.hibernate.envers.store_data_at_delete=true property) to keep its last values.spring.jpa.properties.* names the user of each revision, filled in byrevinfo from the Spring Security context. Envers calls the listener once per revision, when it creates the revision entity.UserRevisionListener listed the revision numbers 1 to 4, andgetRevisions at revision 2 rebuilt the product as it was then, with price 12.00.find returned each version together with its revision entity and type, including the deletion.forRevisionsOfEntity(Product.class, false, true)
The revision entity is read through methods, as the comment in it says. With the loop reading rev.idrev.usernamerev 0 MOD by null
The spring-data-enversRevisionRepositoryfindRevisions(id)findLastChangeRevision(id)AuditReaderrevinfo
Testing audited entities
- Fix the clock: a
bean that returns a value the test controls, as on this page, lets a test assert exact dates. In production, back it with an injectedDateTimeProvider , and replace that bean in tests.java.time.Clock - Set the user: with Spring Security,
from spring-security-test fills the security context for a test method.@WithMockUser(username = "dana") - Flush before you check: the listener runs when Hibernate writes. In a test that does not commit, call
orsaveAndFlush before reading the fields of an update.flush() - Use @DataJpaTest: it starts only the JPA part of the application, but
on the main application class is still applied. If you put it on a separate configuration class instead, import that class in the test.@EnableJpaAuditing
Choosing an auditing approach
| Approach | Records | Best for |
|---|---|---|
| Spring Data auditing | Latest create and change time and user | Most applications; testable with a fixed clock |
@CreationTimestamp@UpdateTimestamp | Latest times only | Simple timestamps without any setup |
JPA @PrePersist@PreUpdate | Whatever the method sets | Derived values, or auditing without Spring Data |
| Hibernate Envers | Every version of every row | Regulated data and "show the history" features |
| Database triggers | Anything, for every client | Tables also written by scripts or other applications |
Whichever you choose, remember that the first four only see changes made through JPA entities. The save()