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
@@ -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);
}
}
}