jpa-auditing: Spring Data JPA auditing on Boot 4.1 - @CreatedDate/@LastModifiedBy, AuditorAware with Spring Security, Instant vs LocalDateTime, Envers

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b8789qiV9Fsv2FqZde
This commit is contained in:
Claude
2026-11-17 23:23:12 +05:30
parent 49146b46e3
commit 260c8a692f
49 changed files with 1170 additions and 0 deletions
+1
View File
@@ -11,6 +11,7 @@ Companion code for a series of posts on [ankurm.com](https://ankurm.com) coverin
| [`r2dbc/`](./r2dbc) | Reactive Data Access with Spring Data R2DBC: CRUD, Transactions and When to Choose It | Spring Data R2DBC 4.1.2, r2dbc-postgresql 1.1.3.RELEASE, PostgreSQL 17 (Testcontainers 2.0.5) | | [`r2dbc/`](./r2dbc) | Reactive Data Access with Spring Data R2DBC: CRUD, Transactions and When to Choose It | Spring Data R2DBC 4.1.2, r2dbc-postgresql 1.1.3.RELEASE, PostgreSQL 17 (Testcontainers 2.0.5) |
| [`projections/`](./projections) | Spring Data JPA Projections: Interface, Record and Dynamic Projections (With the SQL They Generate) | Spring Data JPA 4.1.2, Hibernate 7.4.13.Final, H2 2.4.240 | | [`projections/`](./projections) | Spring Data JPA Projections: Interface, Record and Dynamic Projections (With the SQL They Generate) | Spring Data JPA 4.1.2, Hibernate 7.4.13.Final, H2 2.4.240 |
| [`pagination/`](./pagination) | Spring Data JPA Pagination and Sorting: Page vs Slice vs Keyset Scrolling (Window API) | Spring Data JPA 4.1.2, Hibernate 7.4.13.Final, H2 2.4.240 | | [`pagination/`](./pagination) | Spring Data JPA Pagination and Sorting: Page vs Slice vs Keyset Scrolling (Window API) | Spring Data JPA 4.1.2, Hibernate 7.4.13.Final, H2 2.4.240 |
| [`jpa-auditing/`](./jpa-auditing) | JPA Auditing in Spring Boot 4: @CreatedDate, @LastModifiedBy and the Current User | Spring Data JPA 4.1.2, Spring Security 7.1.2, Hibernate 7.4.13.Final (+ Envers), H2 2.4.240 |
Each module has its own `pom.xml`, a `docker-compose.yml` for its backing services, and a `docs/output/` directory holding the real, re-runnable transcripts that every number quoted in its post traces back to. There are no narrative doc chapters here &mdash; the deeper material for each post lives in accordions inside the post itself. Each module has its own `pom.xml`, a `docker-compose.yml` for its backing services, and a `docs/output/` directory holding the real, re-runnable transcripts that every number quoted in its post traces back to. There are no narrative doc chapters here &mdash; the deeper material for each post lives in accordions inside the post itself.
+1
View File
@@ -0,0 +1 @@
target/
+47
View File
@@ -0,0 +1,47 @@
# jpa-auditing
Companion code for **JPA Auditing in Spring Boot 4: @CreatedDate, @LastModifiedBy and the Current User** on [ankurm.com](https://ankurm.com).
| Component | Version |
|---|---|
| Spring Boot | 4.1.2 |
| Spring Data JPA / Commons | 4.1.2 / 4.1.2 |
| Spring Framework | 7.0.10 |
| Spring Security | 7.1.2 |
| Hibernate ORM / Envers | 7.4.13.Final / 7.4.13.Final |
| H2 (in-memory) | 2.4.240 |
| JDK | Temurin 25.0.5 LTS |
No Docker needed. Every test writes what it saw to `output/` while asserting the same facts, so the numbers in the post fail the build if they stop being true. Timestamps are deterministic because `AuditingConfig` supplies a settable `DateTimeProvider` clock.
```bash
./scripts/run-all.sh # regenerates every file in output/
./scripts/time-zones.sh # only the Instant vs LocalDateTime transcript, under three JVM zones
```
Surefire forks a fresh JVM per test class (`reuseForks=false`) on purpose: the "auditing not enabled" test is only trustworthy in a JVM that never started a context with auditing on.
| Source file | What it shows |
|---|---|
| `AuditingConfig` | `@EnableJpaAuditing` with an `AuditorAware` and a `DateTimeProvider`; the demo switches |
| `Auditable` | the four audit columns in a `@MappedSuperclass` with `AuditingEntityListener` |
| `SecurityContextAuditorAware` | the safe `AuditorAware` (empty for anonymous) |
| `NaiveAuditorAware` | the common version that stores `anonymousUser` |
| `ArticleRepository` | bulk `@Modifying` updates that bypass auditing, and the stamped fix |
| `LocalStamp` | `LocalDateTime` vs `Instant` for the same `@CreatedDate` |
| `ForgottenListener` | an entity that forgot `@EntityListeners` |
| `Document`, `AuditRevision`, `UsernameRevisionListener` | Envers history with the user per revision |
| Transcript | Shows |
|---|---|
| `output/01-create-update.txt` | what is written on create and on update, and the UPDATE SQL |
| `output/02-no-change-no-stamp.txt` | an unchanged entity is not touched |
| `output/03-bulk-update-bypass.txt` | a bulk update skips auditing; the stamped version does not |
| `output/04-auditing-not-enabled.txt` | no `@EnableJpaAuditing`: annotations are inert |
| `output/05-missing-entity-listener.txt` | missing `@EntityListeners`: null, no error |
| `output/06-naive-auditor-anonymous.txt` | the `anonymousUser` trap |
| `output/07-safe-auditor-two-users.txt` | anonymous, alice and bob over HTTP Basic |
| `output/08-other-thread.txt` | the user is lost on another thread unless the context is carried |
| `output/09-instant-vs-localdatetime-*.txt` | the same moment in three JVM zones |
| `output/10-envers-history.txt` | one revision per change, with the user |
| `output/11-modifying-needs-transaction.txt` | a custom `@Modifying` method needs `@Transactional` |
+8
View File
@@ -0,0 +1,8 @@
# 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=?
@@ -0,0 +1,3 @@
# 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)
@@ -0,0 +1,6 @@
# @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
@@ -0,0 +1,4 @@
# 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
@@ -0,0 +1,3 @@
# @EnableJpaAuditing is ON, but the entity has @CreatedDate and no @EntityListeners
saved id=1 createdAt=null
exception: none
@@ -0,0 +1,2 @@
# 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"}
@@ -0,0 +1,8 @@
# 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"}
+5
View File
@@ -0,0 +1,5 @@
# 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
@@ -0,0 +1,5 @@
JVM zone: America/New_York (clock instant: 2026-11-17T08:00:00Z)
column CREATED_INSTANT : TIMESTAMP WITH TIME ZONE
column CREATED_LOCAL : TIMESTAMP
stored LocalDateTime : 2026-11-17T03:00
stored Instant : 2026-11-17T08:00:00Z
@@ -0,0 +1,5 @@
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
@@ -0,0 +1,5 @@
JVM zone: UTC (clock instant: 2026-11-17T08:00:00Z)
column CREATED_INSTANT : TIMESTAMP WITH TIME ZONE
column CREATED_LOCAL : TIMESTAMP
stored LocalDateTime : 2026-11-17T08:00
stored Instant : 2026-11-17T08:00:00Z
@@ -0,0 +1,7 @@
# 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
@@ -0,0 +1,3 @@
# @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
+81
View File
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.2</version>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>jpa-auditing-demo</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<!-- JVM zone for the tests; scripts/time-zones.sh overrides it with -Dtest.tz=... -->
<test.tz>UTC</test.tz>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-envers</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- a fresh JVM per test class: auditing state must not leak between Spring contexts -->
<reuseForks>false</reuseForks>
<argLine>-Duser.timezone=${test.tz}</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Regenerates every file in output/ by running the test suite (in-memory H2, no Docker needed).
set -euo pipefail
cd "$(dirname "$0")/.."
rm -f output/*.txt
mvn -B -q test
./scripts/time-zones.sh >/dev/null
echo "wrote:"; ls output
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Runs TimeTypesTest under three JVM time zones; each writes output/09-instant-vs-localdatetime-<zone>.txt
set -euo pipefail
cd "$(dirname "$0")/.."
for tz in UTC Asia/Kolkata America/New_York; do
mvn -B -q test -Dtest=TimeTypesTest -Dtest.tz="$tz" >/dev/null
done
ls output | grep 09-
@@ -0,0 +1,30 @@
package com.ankurm.jpaauditing;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Article extends Auditable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String body;
protected Article() {}
public Article(String title, String body) {
this.title = title;
this.body = body;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getBody() { return body; }
public void setBody(String body) { this.body = body; }
}
@@ -0,0 +1,43 @@
package com.ankurm.jpaauditing;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ArticleController {
private final ArticleRepository repo;
public ArticleController(ArticleRepository repo) { this.repo = repo; }
public record ArticleRequest(String title, String body) {}
@PostMapping("/articles")
Map<String, Object> create(@RequestBody ArticleRequest r) {
return view(repo.saveAndFlush(new Article(r.title(), r.body())));
}
@PutMapping("/articles/{id}")
Map<String, Object> update(@PathVariable Long id, @RequestBody ArticleRequest r) {
Article a = repo.findById(id).orElseThrow();
a.setTitle(r.title());
a.setBody(r.body());
return view(repo.saveAndFlush(a));
}
private static Map<String, Object> view(Article a) {
Map<String, Object> m = new LinkedHashMap<>();
m.put("id", a.getId());
m.put("title", a.getTitle());
m.put("createdBy", a.getCreatedBy());
m.put("updatedBy", a.getUpdatedBy());
m.put("createdAt", a.getCreatedAt());
m.put("updatedAt", a.getUpdatedAt());
return m;
}
}
@@ -0,0 +1,29 @@
package com.ankurm.jpaauditing;
import java.time.Instant;
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.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface ArticleRepository extends JpaRepository<Article, Long> {
/** Bulk JPQL update: goes straight to SQL, so no entity callback runs and updatedAt is NOT touched. */
@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 where a.id = :id")
int renameBulk(@Param("id") Long id, @Param("title") String title);
/** 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);
/** Same as renameBulk but WITHOUT @Transactional: shows why custom @Modifying methods need one. */
@Modifying(flushAutomatically = true)
@Query("update Article a set a.title = :title where a.id = :id")
int renameBulkNoTx(@Param("id") Long id, @Param("title") String title);
}
@@ -0,0 +1,30 @@
package com.ankurm.jpaauditing;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.hibernate.envers.RevisionEntity;
import org.hibernate.envers.RevisionNumber;
import org.hibernate.envers.RevisionTimestamp;
/** One row per transaction that changed an @Audited entity, plus who did it. */
@Entity
@RevisionEntity(UsernameRevisionListener.class)
public class AuditRevision {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@RevisionNumber
private Long id;
@RevisionTimestamp
private long timestamp;
private String username;
public Long getId() { return id; }
public long getTimestamp() { return timestamp; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
}
@@ -0,0 +1,41 @@
package com.ankurm.jpaauditing;
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
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;
/**
* The four audit columns, written once and inherited. Both annotations are needed:
* the Spring Data annotations say WHAT to fill, AuditingEntityListener says WHEN
* (JPA @PrePersist / @PreUpdate callbacks).
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
@CreatedDate
@Column(nullable = false, updatable = false)
private Instant createdAt;
@LastModifiedDate
@Column(nullable = false)
private Instant updatedAt;
@CreatedBy
@Column(updatable = false)
private String createdBy;
@LastModifiedBy
private String updatedBy;
public Instant getCreatedAt() { return createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public String getCreatedBy() { return createdBy; }
public String getUpdatedBy() { return updatedBy; }
}
@@ -0,0 +1,48 @@
package com.ankurm.jpaauditing;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
/**
* The one switch that turns auditing on. Without @EnableJpaAuditing the annotations on the
* entities are inert and nothing complains. The demo.auditing.enabled property exists only so the
* tests can show that failure; in a real project you would just write the annotation.
*/
@Configuration
@ConditionalOnProperty(name = "demo.auditing.enabled", havingValue = "true", matchIfMissing = true)
@EnableJpaAuditing(auditorAwareRef = "auditorAware", dateTimeProviderRef = "dateTimeProvider")
public class AuditingConfig {
@Bean
@ConditionalOnProperty(name = "demo.auditor", havingValue = "naive")
AuditorAware<String> auditorAware() { return new NaiveAuditorAware(); }
@Bean(name = "auditorAware")
@ConditionalOnProperty(name = "demo.auditor", havingValue = "safe", matchIfMissing = true)
AuditorAware<String> safeAuditorAware() { return new SecurityContextAuditorAware(); }
/** A settable clock so every timestamp in the transcripts is deterministic. */
@Bean
DemoClock demoClock() { return new DemoClock(); }
@Bean
DateTimeProvider dateTimeProvider(DemoClock clock) {
return () -> Optional.of(clock.instant());
}
public static final class DemoClock {
private final AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-11-17T08:00:00Z"));
public Instant instant() { return now.get(); }
public void set(String iso) { now.set(Instant.parse(iso)); }
public Clock asClock() { return Clock.fixed(now.get(), ZoneOffset.UTC); }
}
}
@@ -0,0 +1,37 @@
package com.ankurm.jpaauditing;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.hibernate.envers.Audited;
/**
* Auditing (Spring Data) keeps the LATEST created/modified stamps on the row.
* Envers keeps EVERY version in document_aud. auditParents is needed because the audit
* columns live in a @MappedSuperclass, which Envers skips unless told otherwise.
*/
@Entity
@Audited(auditParents = Auditable.class)
public class Document extends Auditable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String content;
protected Document() {}
public Document(String title, String content) {
this.title = title;
this.content = content;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
}
@@ -0,0 +1,5 @@
package com.ankurm.jpaauditing;
import org.springframework.data.jpa.repository.JpaRepository;
public interface DocumentRepository extends JpaRepository<Document, Long> {}
@@ -0,0 +1,23 @@
package com.ankurm.jpaauditing;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.time.Instant;
import org.springframework.data.annotation.CreatedDate;
/** Annotated like Article, but WITHOUT @EntityListeners(AuditingEntityListener.class). Nothing fills createdAt. */
@Entity
public class ForgottenListener {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CreatedDate
private Instant createdAt;
public Long getId() { return id; }
public Instant getCreatedAt() { return createdAt; }
}
@@ -0,0 +1,5 @@
package com.ankurm.jpaauditing;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ForgottenListenerRepository extends JpaRepository<ForgottenListener, Long> {}
@@ -0,0 +1,11 @@
package com.ankurm.jpaauditing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JpaAuditingApplication {
public static void main(String[] args) {
SpringApplication.run(JpaAuditingApplication.class, args);
}
}
@@ -0,0 +1,31 @@
package com.ankurm.jpaauditing;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.time.Instant;
import java.time.LocalDateTime;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
/** The same moment stored twice: once as LocalDateTime (no zone), once as Instant (a point on the timeline). */
@Entity
@EntityListeners(AuditingEntityListener.class)
public class LocalStamp {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CreatedDate
private LocalDateTime createdLocal;
@CreatedDate
private Instant createdInstant;
public Long getId() { return id; }
public LocalDateTime getCreatedLocal() { return createdLocal; }
public Instant getCreatedInstant() { return createdInstant; }
}
@@ -0,0 +1,5 @@
package com.ankurm.jpaauditing;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LocalStampRepository extends JpaRepository<LocalStamp, Long> {}
@@ -0,0 +1,19 @@
package com.ankurm.jpaauditing;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* The version most tutorials show. It looks correct and is wrong: an unauthenticated request
* carries an AnonymousAuthenticationToken whose getName() is the literal string "anonymousUser",
* so that string lands in created_by.
*/
public class NaiveAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getName);
}
}
@@ -0,0 +1,30 @@
package com.ankurm.jpaauditing;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
/** Demo-only: every request is allowed through, so an unauthenticated call carries the anonymous token. */
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain chain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.anyRequest().permitAll())
.csrf(c -> c.disable()) // demo only; keep CSRF on for browser-facing apps
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
UserDetailsService users() {
return new InMemoryUserDetailsManager(
User.withUsername("alice").password("{noop}pw").roles("USER").build(),
User.withUsername("bob").password("{noop}pw").roles("USER").build());
}
}
@@ -0,0 +1,23 @@
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;
/**
* Returns the logged-in username, or Optional.empty() when there is no real user
* (no authentication, not authenticated, or the anonymous token). Empty means
* "leave createdBy / updatedBy alone", which for a new row means NULL.
*/
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());
}
}
@@ -0,0 +1,24 @@
package com.ankurm.jpaauditing;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.hibernate.resource.jdbc.spi.StatementInspector;
/**
* Records every SQL string Hibernate is about to send to the database.
* Registered through hibernate.session_factory.statement_inspector in application.properties.
* Hibernate instantiates it itself, so the captured list has to be static.
*/
public class SqlRecorder implements StatementInspector {
private static final List<String> CAPTURED = new CopyOnWriteArrayList<>();
@Override
public String inspect(String sql) {
CAPTURED.add(sql);
return sql;
}
public static void clear() { CAPTURED.clear(); }
public static List<String> captured() { return List.copyOf(CAPTURED); }
}
@@ -0,0 +1,14 @@
package com.ankurm.jpaauditing;
import org.hibernate.envers.RevisionListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/** Envers' own hook: called once per revision, so it is where the current user is attached. */
public class UsernameRevisionListener implements RevisionListener {
@Override
public void newRevision(Object revisionEntity) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
((AuditRevision) revisionEntity).setUsername(auth == null ? null : auth.getName());
}
}
@@ -0,0 +1,10 @@
spring.datasource.url=jdbc:h2:mem:auditing;DB_CLOSE_DELAY=-1
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.open-in-view=false
# Every SQL statement is captured by SqlRecorder (a Hibernate StatementInspector), not by show_sql.
spring.jpa.properties.hibernate.session_factory.statement_inspector=com.ankurm.jpaauditing.SqlRecorder
# Switches used by the tests to show the failure modes (see AuditingConfig):
# demo.auditing.enabled=false -> @EnableJpaAuditing is absent
# demo.auditor=naive -> the AuditorAware that stores "anonymousUser"
demo.auditing.enabled=true
demo.auditor=safe
@@ -0,0 +1,34 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.test.context.support.WithMockUser;
/** Transcript 04: no @EnableJpaAuditing, so the annotations on the entity are inert. */
@SpringBootTest(properties = "demo.auditing.enabled=false")
class AuditingNotEnabledTest {
@Autowired ArticleRepository repo;
@Autowired(required = false) AuditingConfig config;
@Test
@WithMockUser("alice")
void annotationsAreInert() {
Transcript t = new Transcript("04-auditing-not-enabled.txt");
t.line("# demo.auditing.enabled=false (i.e. no @EnableJpaAuditing)");
t.line("AuditingConfig bean present: %s", config != null);
Throwable thrown = catchThrowable(() -> repo.saveAndFlush(new Article("No auditing", "x")));
t.line("save() threw: %s", thrown == null ? "nothing" : thrown.getClass().getName());
Throwable root = thrown;
while (root != null && root.getCause() != null && root.getCause() != root) root = root.getCause();
t.line("root cause: %s", root == null ? "-" : root.getMessage().lines().findFirst().orElse(""));
assertThat(config).isNull();
assertThat(thrown).isInstanceOf(DataIntegrityViolationException.class);
t.write();
}
}
@@ -0,0 +1,116 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
/** Transcripts 01-03: what auditing writes on create, on update, on a no-op save, and on a bulk update. */
@SpringBootTest
class CreateUpdateTest {
@Autowired ArticleRepository repo;
@Autowired AuditingConfig.DemoClock clock;
@BeforeEach
void clean() { repo.deleteAll(); SqlRecorder.clear(); }
@Test
@WithMockUser("alice")
void createThenUpdate() {
clock.set("2026-11-17T08:00:00Z");
Article saved = repo.saveAndFlush(new Article("Hello", "first draft"));
Transcript t = new Transcript("01-create-update.txt");
t.line("# create as alice at 2026-11-17T08:00:00Z");
t.line("createdAt=%s updatedAt=%s", saved.getCreatedAt(), saved.getUpdatedAt());
t.line("createdBy=%s updatedBy=%s", saved.getCreatedBy(), saved.getUpdatedBy());
assertThat(saved.getCreatedAt()).isEqualTo(Instant.parse("2026-11-17T08:00:00Z"));
assertThat(saved.getUpdatedAt()).isEqualTo(saved.getCreatedAt()); // modifyOnCreate defaults to true
assertThat(saved.getCreatedBy()).isEqualTo("alice");
assertThat(saved.getUpdatedBy()).isEqualTo("alice");
// a different user edits it two hours later
clock.set("2026-11-17T10:00:00Z");
SqlRecorder.clear();
Article a = repo.findById(saved.getId()).orElseThrow();
a.setBody("second draft");
Article after = editAs("bob", a);
t.line("");
t.line("# update as bob at 2026-11-17T10:00:00Z");
t.line("createdAt=%s updatedAt=%s", after.getCreatedAt(), after.getUpdatedAt());
t.line("createdBy=%s updatedBy=%s", after.getCreatedBy(), after.getUpdatedBy());
List<String> sql = SqlRecorder.captured().stream().filter(s -> s.startsWith("update")).toList();
t.line("UPDATE SQL: %s", sql.get(0));
assertThat(after.getCreatedAt()).isEqualTo(Instant.parse("2026-11-17T08:00:00Z"));
assertThat(after.getUpdatedAt()).isEqualTo(Instant.parse("2026-11-17T10:00:00Z"));
assertThat(after.getCreatedBy()).isEqualTo("alice");
assertThat(after.getUpdatedBy()).isEqualTo("bob");
assertThat(sql.get(0)).doesNotContain("created_at").doesNotContain("created_by");
t.write();
}
@Test
@WithMockUser("alice")
void noChangeNoStamp() {
clock.set("2026-11-17T08:00:00Z");
Article saved = repo.saveAndFlush(new Article("Same", "same"));
clock.set("2026-11-17T12:00:00Z");
SqlRecorder.clear();
Article a = repo.findById(saved.getId()).orElseThrow();
a.setTitle("Same"); // identical value
Article again = repo.saveAndFlush(a);
long updates = SqlRecorder.captured().stream().filter(s -> s.startsWith("update")).count();
Transcript t = new Transcript("02-no-change-no-stamp.txt");
t.line("# save an entity whose fields did not change, clock moved to 12:00Z");
t.line("UPDATE statements issued: %d", updates);
t.line("updatedAt=%s (still the create time)", again.getUpdatedAt());
assertThat(updates).isZero();
assertThat(again.getUpdatedAt()).isEqualTo(Instant.parse("2026-11-17T08:00:00Z"));
t.write();
}
@Test
@WithMockUser("alice")
void bulkUpdateBypassesAuditing() {
clock.set("2026-11-17T08:00:00Z");
Long id = repo.saveAndFlush(new Article("Original", "x")).getId();
clock.set("2026-11-17T09:30:00Z");
SqlRecorder.clear();
repo.renameBulk(id, "Renamed (bulk)");
Article afterBulk = repo.findById(id).orElseThrow();
Transcript t = new Transcript("03-bulk-update-bypass.txt");
t.line("# @Modifying JPQL update at 09:30Z as alice");
t.line("SQL: %s", SqlRecorder.captured().stream().filter(s -> s.startsWith("update")).findFirst().orElseThrow());
t.line("title=%s updatedAt=%s updatedBy=%s", afterBulk.getTitle(), afterBulk.getUpdatedAt(), afterBulk.getUpdatedBy());
assertThat(afterBulk.getTitle()).isEqualTo("Renamed (bulk)");
assertThat(afterBulk.getUpdatedAt()).isEqualTo(Instant.parse("2026-11-17T08:00:00Z"));
clock.set("2026-11-17T09:45:00Z");
repo.renameBulkStamped(id, "Renamed (stamped)", clock.instant(), "alice");
Article fixed = repo.findById(id).orElseThrow();
t.line("");
t.line("# the same update, setting the audit columns in the query itself, at 09:45Z");
t.line("title=%s updatedAt=%s updatedBy=%s", fixed.getTitle(), fixed.getUpdatedAt(), fixed.getUpdatedBy());
assertThat(fixed.getUpdatedAt()).isEqualTo(Instant.parse("2026-11-17T09:45:00Z"));
t.write();
}
/** Runs the update with a different current user, then restores the caller's context. */
private Article editAs(String user, Article a) {
var original = org.springframework.security.core.context.SecurityContextHolder.getContext();
try {
var ctx = org.springframework.security.core.context.SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(org.springframework.security.authentication.UsernamePasswordAuthenticationToken
.authenticated(user, "n/a", List.of()));
org.springframework.security.core.context.SecurityContextHolder.setContext(ctx);
return repo.saveAndFlush(a);
} finally {
org.springframework.security.core.context.SecurityContextHolder.setContext(original);
}
}
}
@@ -0,0 +1,64 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManager;
import java.util.List;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.support.TransactionTemplate;
/** Transcript 10: Spring Data auditing keeps the latest stamps; Envers keeps every version and who made it. */
@SpringBootTest
class EnversHistoryTest {
@Autowired DocumentRepository repo;
@Autowired EntityManager em;
@Autowired TransactionTemplate tx;
@Autowired AuditingConfig.DemoClock clock;
@Test
void everyVersionIsKept() {
clock.set("2026-11-17T08:00:00Z");
Long id = Users.as("alice", () -> repo.saveAndFlush(new Document("Spec", "v1")).getId());
clock.set("2026-11-17T09:00:00Z");
Users.as("bob", () -> edit(id, "v2"));
clock.set("2026-11-17T10:00:00Z");
Users.as("alice", () -> edit(id, "v3"));
Transcript t = new Transcript("10-envers-history.txt");
Document now = repo.findById(id).orElseThrow();
t.line("# the row itself (Spring Data auditing): only the latest stamps");
t.line("content=%s createdBy=%s updatedBy=%s updatedAt=%s", now.getContent(), now.getCreatedBy(),
now.getUpdatedBy(), now.getUpdatedAt());
t.line("");
t.line("# the history (Envers): one row per revision");
List<String> lines = tx.execute(s -> {
AuditReader reader = AuditReaderFactory.get(em);
return reader.getRevisions(Document.class, id).stream().map(rev -> {
Document d = reader.find(Document.class, id, rev);
AuditRevision r = reader.findRevision(AuditRevision.class, rev);
return "rev %d revision.username=%-5s content=%s updatedBy=%-5s updatedAt=%s"
.formatted(rev.longValue(), r.getUsername(), d.getContent(), d.getUpdatedBy(), d.getUpdatedAt());
}).toList();
});
lines.forEach(t::line);
assertThat(lines).hasSize(3);
assertThat(lines.get(0)).contains("username=alice").contains("content=v1");
assertThat(lines.get(1)).contains("username=bob").contains("content=v2");
assertThat(lines.get(2)).contains("username=alice").contains("content=v3");
t.write();
}
private Long edit(Long id, String content) {
return tx.execute(s -> {
Document d = repo.findById(id).orElseThrow();
d.setContent(content);
return d.getId();
});
}
}
@@ -0,0 +1,27 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
/** Transcript 05: auditing is ON, but the entity forgot @EntityListeners. */
@SpringBootTest
class MissingListenerTest {
@Autowired ForgottenListenerRepository repo;
@Test
@WithMockUser("alice")
void listenerMissingMeansNullAndNoError() {
ForgottenListener saved = repo.saveAndFlush(new ForgottenListener());
Transcript t = new Transcript("05-missing-entity-listener.txt");
t.line("# @EnableJpaAuditing is ON, but the entity has @CreatedDate and no @EntityListeners");
t.line("saved id=%d createdAt=%s", saved.getId(), saved.getCreatedAt());
t.line("exception: none");
assertThat(saved.getCreatedAt()).isNull();
t.write();
}
}
@@ -0,0 +1,29 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
/** Transcript 11: a custom @Modifying method called outside a transaction. */
@SpringBootTest
class ModifyingNeedsTransactionTest {
@Autowired ArticleRepository repo;
@Test
@WithMockUser("alice")
void modifyingWithoutTransactionFails() {
Long id = repo.saveAndFlush(new Article("t", "b")).getId();
Throwable thrown = catchThrowable(() -> repo.renameBulkNoTx(id, "x"));
Transcript t = new Transcript("11-modifying-needs-transaction.txt");
t.line("# @Modifying(flushAutomatically = true) method with no @Transactional, called from plain code");
t.line("exception: %s", thrown.getClass().getName());
t.line("message : %s", thrown.getMessage());
assertThat(thrown).isInstanceOf(org.springframework.dao.InvalidDataAccessApiUsageException.class);
t.write();
}
}
@@ -0,0 +1,31 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
/** Transcript 06: the tutorial AuditorAware stores the literal string "anonymousUser". */
@SpringBootTest(properties = "demo.auditor=naive")
@AutoConfigureMockMvc
class NaiveAuditorTest {
@Autowired MockMvc mvc;
@Test
void anonymousRequestStoresTheLiteralAnonymousUser() throws Exception {
String body = mvc.perform(post("/articles").contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"From REST\",\"body\":\"b\"}"))
.andReturn().getResponse().getContentAsString();
Transcript t = new Transcript("06-naive-auditor-anonymous.txt");
t.line("# demo.auditor=naive, POST /articles with NO credentials");
t.line(body);
assertThat(body).contains("\"createdBy\":\"anonymousUser\"");
t.write();
}
}
@@ -0,0 +1,53 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.concurrent.DelegatingSecurityContextExecutor;
import org.springframework.security.test.context.support.WithMockUser;
/** Transcript 08: the SecurityContext does not follow work onto another thread unless you carry it. */
@SpringBootTest
class OtherThreadTest {
@Autowired AuditorAware<String> auditor;
@Autowired ArticleRepository repo;
@Test
@WithMockUser("alice")
void securityContextDoesNotFollowYouToAnotherThread() throws Exception {
var pool = Executors.newSingleThreadExecutor();
try {
Optional<String> here = auditor.getCurrentAuditor();
Optional<String> there = CompletableFuture.supplyAsync(() -> auditor.getCurrentAuditor(), pool).get();
Long plainId = CompletableFuture.supplyAsync(
() -> repo.saveAndFlush(new Article("from pool", "x")).getId(), pool).get();
var delegating = new DelegatingSecurityContextExecutor(pool);
Long delegatedId = CompletableFuture.supplyAsync(
() -> repo.saveAndFlush(new Article("from delegating pool", "x")).getId(), delegating).get();
Transcript t = new Transcript("08-other-thread.txt");
t.line("# test method runs as alice");
t.line("auditor on the request thread : %s", here);
t.line("auditor on a plain pool thread: %s", there);
t.line("createdBy of row saved on a plain pool thread : %s",
repo.findById(plainId).orElseThrow().getCreatedBy());
t.line("createdBy of row saved via DelegatingSecurityContextExecutor: %s",
repo.findById(delegatedId).orElseThrow().getCreatedBy());
assertThat(here).contains("alice");
assertThat(there).isEmpty();
assertThat(repo.findById(plainId).orElseThrow().getCreatedBy()).isNull();
assertThat(repo.findById(delegatedId).orElseThrow().getCreatedBy()).isEqualTo("alice");
t.write();
} finally {
pool.shutdownNow();
}
}
}
@@ -0,0 +1,50 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
/** Transcript 07: the safe AuditorAware over real HTTP Basic requests. */
@SpringBootTest
@AutoConfigureMockMvc
class SafeAuditorTest {
private static final String JSON = "{\"title\":\"From REST\",\"body\":\"b\"}";
@Autowired MockMvc mvc;
@Test
void anonymousRequestLeavesNullAndRealUsersAreTracked() throws Exception {
Transcript t = new Transcript("07-safe-auditor-two-users.txt");
String anon = mvc.perform(post("/articles").contentType(MediaType.APPLICATION_JSON).content(JSON))
.andReturn().getResponse().getContentAsString();
t.line("# demo.auditor=safe, POST /articles with NO credentials");
t.line(anon);
assertThat(anon).contains("\"createdBy\":null");
String created = mvc.perform(post("/articles").with(httpBasic("alice", "pw"))
.contentType(MediaType.APPLICATION_JSON).content(JSON)).andReturn().getResponse().getContentAsString();
t.line("");
t.line("# POST as alice (HTTP Basic)");
t.line(created);
String id = created.replaceAll(".*\"id\":(\\d+).*", "$1");
String updated = mvc.perform(put("/articles/" + id).with(httpBasic("bob", "pw"))
.contentType(MediaType.APPLICATION_JSON).content("{\"title\":\"Edited by bob\",\"body\":\"b2\"}"))
.andReturn().getResponse().getContentAsString();
t.line("");
t.line("# PUT as bob");
t.line(updated);
assertThat(created).contains("\"createdBy\":\"alice\"").contains("\"updatedBy\":\"alice\"");
assertThat(updated).contains("\"createdBy\":\"alice\"").contains("\"updatedBy\":\"bob\"");
t.write();
}
}
@@ -0,0 +1,46 @@
package com.ankurm.jpaauditing;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* Transcript 09-*: the same Instant saved from a JVM running in different time zones.
* The zone comes from -Duser.timezone (pom property test.tz); scripts/time-zones.sh runs three.
*/
@SpringBootTest
class TimeTypesTest {
@Autowired LocalStampRepository repo;
@Autowired AuditingConfig.DemoClock clock;
@Autowired JdbcTemplate jdbc;
@Test
void localDateTimeDependsOnTheJvmZoneInstantDoesNot() {
ZoneId zone = ZoneId.systemDefault();
Instant moment = Instant.parse("2026-11-17T08:00:00Z");
clock.set(moment.toString());
LocalStamp saved = repo.saveAndFlush(new LocalStamp());
LocalStamp row = repo.findById(saved.getId()).orElseThrow();
Transcript t = new Transcript("09-instant-vs-localdatetime-" + zone.getId().replace('/', '-') + ".txt");
t.line("JVM zone: %s (clock instant: %s)", zone, moment);
List<Map<String, Object>> cols = jdbc.queryForList(
"select column_name, data_type from information_schema.columns "
+ "where table_name = 'LOCAL_STAMP' and column_name like 'CREATED%' order by column_name");
cols.forEach(c -> t.line("column %s : %s", c.get("COLUMN_NAME"), c.get("DATA_TYPE")));
t.line("stored LocalDateTime : %s", row.getCreatedLocal());
t.line("stored Instant : %s", row.getCreatedInstant());
assertThat(row.getCreatedInstant()).isEqualTo(moment);
assertThat(row.getCreatedLocal()).isEqualTo(LocalDateTime.ofInstant(moment, zone));
t.write();
}
}
@@ -0,0 +1,29 @@
package com.ankurm.jpaauditing;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Writes output/NN-*.txt while a test asserts the same facts. */
final class Transcript {
private final List<String> lines = new ArrayList<>();
private final Path file;
Transcript(String name) { this.file = Path.of("output/" + name); }
Transcript line(String fmt, Object... args) {
String s = args.length == 0 ? fmt : fmt.formatted(args);
lines.add(s);
System.out.println(s);
return this;
}
void write() {
try {
Files.createDirectories(file.getParent());
Files.writeString(file, String.join("\n", lines) + "\n");
} catch (IOException e) { throw new RuntimeException(e); }
}
}
@@ -0,0 +1,23 @@
package com.ankurm.jpaauditing;
import java.util.List;
import java.util.function.Supplier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
/** Runs a block with a given user in the SecurityContext, then restores whatever was there. */
final class Users {
private Users() {}
static <T> T as(String user, Supplier<T> work) {
var original = SecurityContextHolder.getContext();
try {
var ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(UsernamePasswordAuthenticationToken.authenticated(user, "n/a", List.of()));
SecurityContextHolder.setContext(ctx);
return work.get();
} finally {
SecurityContextHolder.setContext(original);
}
}
}