diff --git a/README.md b/README.md index 6dfada5..5073af8 100644 --- a/README.md +++ b/README.md @@ -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) | | [`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 | +| [`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 — the deeper material for each post lives in accordions inside the post itself. diff --git a/jpa-auditing/.gitignore b/jpa-auditing/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/jpa-auditing/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/jpa-auditing/README.md b/jpa-auditing/README.md new file mode 100644 index 0000000..b7afdfc --- /dev/null +++ b/jpa-auditing/README.md @@ -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` | diff --git a/jpa-auditing/output/01-create-update.txt b/jpa-auditing/output/01-create-update.txt new file mode 100644 index 0000000..b4aef8e --- /dev/null +++ b/jpa-auditing/output/01-create-update.txt @@ -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=? diff --git a/jpa-auditing/output/02-no-change-no-stamp.txt b/jpa-auditing/output/02-no-change-no-stamp.txt new file mode 100644 index 0000000..ed5c3a8 --- /dev/null +++ b/jpa-auditing/output/02-no-change-no-stamp.txt @@ -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) diff --git a/jpa-auditing/output/03-bulk-update-bypass.txt b/jpa-auditing/output/03-bulk-update-bypass.txt new file mode 100644 index 0000000..e87f379 --- /dev/null +++ b/jpa-auditing/output/03-bulk-update-bypass.txt @@ -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 diff --git a/jpa-auditing/output/04-auditing-not-enabled.txt b/jpa-auditing/output/04-auditing-not-enabled.txt new file mode 100644 index 0000000..9976cbb --- /dev/null +++ b/jpa-auditing/output/04-auditing-not-enabled.txt @@ -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 diff --git a/jpa-auditing/output/05-missing-entity-listener.txt b/jpa-auditing/output/05-missing-entity-listener.txt new file mode 100644 index 0000000..3fe5af8 --- /dev/null +++ b/jpa-auditing/output/05-missing-entity-listener.txt @@ -0,0 +1,3 @@ +# @EnableJpaAuditing is ON, but the entity has @CreatedDate and no @EntityListeners +saved id=1 createdAt=null +exception: none diff --git a/jpa-auditing/output/06-naive-auditor-anonymous.txt b/jpa-auditing/output/06-naive-auditor-anonymous.txt new file mode 100644 index 0000000..c13309a --- /dev/null +++ b/jpa-auditing/output/06-naive-auditor-anonymous.txt @@ -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"} diff --git a/jpa-auditing/output/07-safe-auditor-two-users.txt b/jpa-auditing/output/07-safe-auditor-two-users.txt new file mode 100644 index 0000000..0892b45 --- /dev/null +++ b/jpa-auditing/output/07-safe-auditor-two-users.txt @@ -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"} diff --git a/jpa-auditing/output/08-other-thread.txt b/jpa-auditing/output/08-other-thread.txt new file mode 100644 index 0000000..8813de2 --- /dev/null +++ b/jpa-auditing/output/08-other-thread.txt @@ -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 diff --git a/jpa-auditing/output/09-instant-vs-localdatetime-America-New_York.txt b/jpa-auditing/output/09-instant-vs-localdatetime-America-New_York.txt new file mode 100644 index 0000000..194f93c --- /dev/null +++ b/jpa-auditing/output/09-instant-vs-localdatetime-America-New_York.txt @@ -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 diff --git a/jpa-auditing/output/09-instant-vs-localdatetime-Asia-Kolkata.txt b/jpa-auditing/output/09-instant-vs-localdatetime-Asia-Kolkata.txt new file mode 100644 index 0000000..e505ce0 --- /dev/null +++ b/jpa-auditing/output/09-instant-vs-localdatetime-Asia-Kolkata.txt @@ -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 diff --git a/jpa-auditing/output/09-instant-vs-localdatetime-UTC.txt b/jpa-auditing/output/09-instant-vs-localdatetime-UTC.txt new file mode 100644 index 0000000..aba423a --- /dev/null +++ b/jpa-auditing/output/09-instant-vs-localdatetime-UTC.txt @@ -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 diff --git a/jpa-auditing/output/10-envers-history.txt b/jpa-auditing/output/10-envers-history.txt new file mode 100644 index 0000000..8fd41ca --- /dev/null +++ b/jpa-auditing/output/10-envers-history.txt @@ -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 diff --git a/jpa-auditing/output/11-modifying-needs-transaction.txt b/jpa-auditing/output/11-modifying-needs-transaction.txt new file mode 100644 index 0000000..9eeb5e4 --- /dev/null +++ b/jpa-auditing/output/11-modifying-needs-transaction.txt @@ -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 diff --git a/jpa-auditing/pom.xml b/jpa-auditing/pom.xml new file mode 100644 index 0000000..18d3ef5 --- /dev/null +++ b/jpa-auditing/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.2 + + + com.ankurm + jpa-auditing-demo + 1.0.0 + jar + + + 25 + 25 + + UTC + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-security + + + org.hibernate.orm + hibernate-envers + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + org.springframework.boot + spring-boot-starter-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + false + -Duser.timezone=${test.tz} + + + + + diff --git a/jpa-auditing/scripts/run-all.sh b/jpa-auditing/scripts/run-all.sh new file mode 100755 index 0000000..bd2770b --- /dev/null +++ b/jpa-auditing/scripts/run-all.sh @@ -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 diff --git a/jpa-auditing/scripts/time-zones.sh b/jpa-auditing/scripts/time-zones.sh new file mode 100755 index 0000000..53e3bb3 --- /dev/null +++ b/jpa-auditing/scripts/time-zones.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Runs TimeTypesTest under three JVM time zones; each writes output/09-instant-vs-localdatetime-.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- diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Article.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Article.java new file mode 100644 index 0000000..546ade2 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Article.java @@ -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; } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ArticleController.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ArticleController.java new file mode 100644 index 0000000..6eb6471 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ArticleController.java @@ -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 create(@RequestBody ArticleRequest r) { + return view(repo.saveAndFlush(new Article(r.title(), r.body()))); + } + + @PutMapping("/articles/{id}") + Map 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 view(Article a) { + Map 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; + } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ArticleRepository.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ArticleRepository.java new file mode 100644 index 0000000..f108d5e --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ArticleRepository.java @@ -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 { + + /** 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); +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/AuditRevision.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/AuditRevision.java new file mode 100644 index 0000000..f2045c9 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/AuditRevision.java @@ -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; } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Auditable.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Auditable.java new file mode 100644 index 0000000..e4aaf0a --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Auditable.java @@ -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; } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/AuditingConfig.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/AuditingConfig.java new file mode 100644 index 0000000..3039293 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/AuditingConfig.java @@ -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 auditorAware() { return new NaiveAuditorAware(); } + + @Bean(name = "auditorAware") + @ConditionalOnProperty(name = "demo.auditor", havingValue = "safe", matchIfMissing = true) + AuditorAware 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 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); } + } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Document.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Document.java new file mode 100644 index 0000000..acda6c9 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/Document.java @@ -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; } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/DocumentRepository.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/DocumentRepository.java new file mode 100644 index 0000000..e922779 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/DocumentRepository.java @@ -0,0 +1,5 @@ +package com.ankurm.jpaauditing; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface DocumentRepository extends JpaRepository {} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ForgottenListener.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ForgottenListener.java new file mode 100644 index 0000000..da9385e --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ForgottenListener.java @@ -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; } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ForgottenListenerRepository.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ForgottenListenerRepository.java new file mode 100644 index 0000000..aba5de6 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/ForgottenListenerRepository.java @@ -0,0 +1,5 @@ +package com.ankurm.jpaauditing; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ForgottenListenerRepository extends JpaRepository {} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/JpaAuditingApplication.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/JpaAuditingApplication.java new file mode 100644 index 0000000..394545c --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/JpaAuditingApplication.java @@ -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); + } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/LocalStamp.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/LocalStamp.java new file mode 100644 index 0000000..4be7232 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/LocalStamp.java @@ -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; } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/LocalStampRepository.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/LocalStampRepository.java new file mode 100644 index 0000000..438c957 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/LocalStampRepository.java @@ -0,0 +1,5 @@ +package com.ankurm.jpaauditing; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface LocalStampRepository extends JpaRepository {} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/NaiveAuditorAware.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/NaiveAuditorAware.java new file mode 100644 index 0000000..7d49f62 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/NaiveAuditorAware.java @@ -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 { + @Override + public Optional getCurrentAuditor() { + return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()) + .map(Authentication::getName); + } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SecurityConfig.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SecurityConfig.java new file mode 100644 index 0000000..42df547 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SecurityConfig.java @@ -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()); + } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SecurityContextAuditorAware.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SecurityContextAuditorAware.java new file mode 100644 index 0000000..2438a81 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SecurityContextAuditorAware.java @@ -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 { + @Override + public Optional getCurrentAuditor() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) { + return Optional.empty(); + } + return Optional.of(auth.getName()); + } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SqlRecorder.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SqlRecorder.java new file mode 100644 index 0000000..fc46344 --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/SqlRecorder.java @@ -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 CAPTURED = new CopyOnWriteArrayList<>(); + + @Override + public String inspect(String sql) { + CAPTURED.add(sql); + return sql; + } + + public static void clear() { CAPTURED.clear(); } + + public static List captured() { return List.copyOf(CAPTURED); } +} diff --git a/jpa-auditing/src/main/java/com/ankurm/jpaauditing/UsernameRevisionListener.java b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/UsernameRevisionListener.java new file mode 100644 index 0000000..40f022e --- /dev/null +++ b/jpa-auditing/src/main/java/com/ankurm/jpaauditing/UsernameRevisionListener.java @@ -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()); + } +} diff --git a/jpa-auditing/src/main/resources/application.properties b/jpa-auditing/src/main/resources/application.properties new file mode 100644 index 0000000..4111d8e --- /dev/null +++ b/jpa-auditing/src/main/resources/application.properties @@ -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 diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/AuditingNotEnabledTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/AuditingNotEnabledTest.java new file mode 100644 index 0000000..33a587b --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/AuditingNotEnabledTest.java @@ -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(); + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/CreateUpdateTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/CreateUpdateTest.java new file mode 100644 index 0000000..bad71ff --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/CreateUpdateTest.java @@ -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 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); + } + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/EnversHistoryTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/EnversHistoryTest.java new file mode 100644 index 0000000..087c22d --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/EnversHistoryTest.java @@ -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 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(); + }); + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/MissingListenerTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/MissingListenerTest.java new file mode 100644 index 0000000..4b22d87 --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/MissingListenerTest.java @@ -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(); + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/ModifyingNeedsTransactionTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/ModifyingNeedsTransactionTest.java new file mode 100644 index 0000000..eaf0644 --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/ModifyingNeedsTransactionTest.java @@ -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(); + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/NaiveAuditorTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/NaiveAuditorTest.java new file mode 100644 index 0000000..6d77f76 --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/NaiveAuditorTest.java @@ -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(); + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/OtherThreadTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/OtherThreadTest.java new file mode 100644 index 0000000..4ff88fe --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/OtherThreadTest.java @@ -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 auditor; + @Autowired ArticleRepository repo; + + @Test + @WithMockUser("alice") + void securityContextDoesNotFollowYouToAnotherThread() throws Exception { + var pool = Executors.newSingleThreadExecutor(); + try { + Optional here = auditor.getCurrentAuditor(); + Optional 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(); + } + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/SafeAuditorTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/SafeAuditorTest.java new file mode 100644 index 0000000..bc18926 --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/SafeAuditorTest.java @@ -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(); + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/TimeTypesTest.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/TimeTypesTest.java new file mode 100644 index 0000000..da481a3 --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/TimeTypesTest.java @@ -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> 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(); + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/Transcript.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/Transcript.java new file mode 100644 index 0000000..4ffc0d4 --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/Transcript.java @@ -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 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); } + } +} diff --git a/jpa-auditing/src/test/java/com/ankurm/jpaauditing/Users.java b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/Users.java new file mode 100644 index 0000000..4fc0c54 --- /dev/null +++ b/jpa-auditing/src/test/java/com/ankurm/jpaauditing/Users.java @@ -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 as(String user, Supplier 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); + } + } +}