From 4f7ebd5cb0d664ff36476085306c978a4cba72d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:12:23 +0530 Subject: [PATCH] Add flush-ordering module: Hibernate 8.0.0.CR2 graph vs legacy flush queue Seven runnable scenarios that record the real JDBC SQL under hibernate.flush.queue.type=legacy and graph: insert order, delete order, unique delete-then-reinsert, unique swap, NOT NULL FK, batching, setting values. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017ic4b3obqqePfZ9m2Jk5Ub --- flush-ordering/README.md | 20 ++ flush-ordering/pom.xml | 51 +++++ flush-ordering/scripts/inspect-settings.sh | 11 + flush-ordering/scripts/run-all.sh | 10 + .../main/java/com/ankurm/flush/Account.java | 26 +++ .../main/java/com/ankurm/flush/Author.java | 24 +++ .../main/java/com/ankurm/flush/Comment.java | 30 +++ .../src/main/java/com/ankurm/flush/Post.java | 29 +++ .../com/ankurm/flush/FlushOrderingTest.java | 200 ++++++++++++++++++ .../src/test/java/com/ankurm/flush/Lab.java | 44 ++++ .../java/com/ankurm/flush/SqlRecorder.java | 95 +++++++++ .../java/com/ankurm/flush/Transcript.java | 44 ++++ 12 files changed, 584 insertions(+) create mode 100644 flush-ordering/README.md create mode 100644 flush-ordering/pom.xml create mode 100755 flush-ordering/scripts/inspect-settings.sh create mode 100755 flush-ordering/scripts/run-all.sh create mode 100644 flush-ordering/src/main/java/com/ankurm/flush/Account.java create mode 100644 flush-ordering/src/main/java/com/ankurm/flush/Author.java create mode 100644 flush-ordering/src/main/java/com/ankurm/flush/Comment.java create mode 100644 flush-ordering/src/main/java/com/ankurm/flush/Post.java create mode 100644 flush-ordering/src/test/java/com/ankurm/flush/FlushOrderingTest.java create mode 100644 flush-ordering/src/test/java/com/ankurm/flush/Lab.java create mode 100644 flush-ordering/src/test/java/com/ankurm/flush/SqlRecorder.java create mode 100644 flush-ordering/src/test/java/com/ankurm/flush/Transcript.java diff --git a/flush-ordering/README.md b/flush-ordering/README.md new file mode 100644 index 0000000..706cf92 --- /dev/null +++ b/flush-ordering/README.md @@ -0,0 +1,20 @@ +# Hibernate 8 graph-based flush ordering + +Runnable companion to the ankurm.com post on Hibernate ORM 8's graph-based flush coordination. +Each test runs the same unit of work against `hibernate.flush.queue.type=legacy` and `graph`, and +records the SQL that actually reached JDBC. The test asserts the same facts the post quotes. + +Tested on Hibernate ORM 8.0.0.CR2 (release candidate, 24 Nov 2026), Jakarta Persistence 4.0.0-M8 +(resolved transitively), H2 2.5.252, Temurin 25.0.5.1, Maven 3.9.11. Pre-release: behaviour may change before GA. + + ./scripts/run-all.sh # runs the tests and prints target/transcripts/*.txt + ./scripts/inspect-settings.sh # prints the real setting names and enum values from the jar + +| File | What it shows | +|---|---| +| `src/main/java/com/ankurm/flush/` | `Author`, `Post` (nullable FK), `Comment` (NOT NULL FK), `Account` (unique email) | +| `src/test/java/com/ankurm/flush/Lab.java` | boots a SessionFactory with the chosen queue type | +| `src/test/java/com/ankurm/flush/SqlRecorder.java` | JDBC wrapper that records SQL with bound values | +| `src/test/java/com/ankurm/flush/FlushOrderingTest.java` | the seven scenarios | + +This module is self-contained; the other module in this repository (`../`) is the EntityAgent demo on CR1. diff --git a/flush-ordering/pom.xml b/flush-ordering/pom.xml new file mode 100644 index 0000000..bca7c4d --- /dev/null +++ b/flush-ordering/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + com.ankurm + hibernate8-flush-ordering + 1.0.0 + Hibernate 8 graph-based flush ordering demo + + + 25 + UTF-8 + 8.0.0.CR2 + 2.5.252 + 6.1.3 + + + + + org.hibernate.orm + hibernate-core + ${hibernate.version} + + + com.h2database + h2 + ${h2.version} + + + org.slf4j + slf4j-simple + 2.0.17 + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.4 + + + + diff --git a/flush-ordering/scripts/inspect-settings.sh b/flush-ordering/scripts/inspect-settings.sh new file mode 100755 index 0000000..6d4588f --- /dev/null +++ b/flush-ordering/scripts/inspect-settings.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Prints the flush settings and queue types straight from the Hibernate jar, so nothing here is quoted from prose. +# Run "mvn -q dependency:resolve" first so the jar is in ~/.m2. Needs a JDK (javap). +set -euo pipefail +JAR=$(find "$HOME/.m2" -name 'hibernate-core-8.0.0.CR2.jar' | head -1) +echo "jar: $(basename "$JAR")" +javap -constants -cp "$JAR" org.hibernate.cfg.FlushSettings 2>/dev/null +javap -cp "$JAR" org.hibernate.action.queue.spi.QueueType 2>/dev/null | grep 'static final .*QueueType [A-Z]*;' +javap -cp "$JAR" 'org.hibernate.action.queue.spi.PlanningOptions$UniqueCycleStrategy' 2>/dev/null | grep 'static final .*UniqueCycleStrategy [A-Z_]*;' +echo "legacy execution order (enum constants, in declaration order):" +javap -p -cp "$JAR" 'org.hibernate.engine.spi.ActionQueueLegacy$OrderedActions' 2>/dev/null | grep -E 'OrderedActions [A-Z][A-Za-z]*;' diff --git a/flush-ordering/scripts/run-all.sh b/flush-ordering/scripts/run-all.sh new file mode 100755 index 0000000..8147573 --- /dev/null +++ b/flush-ordering/scripts/run-all.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Runs the whole suite and prints the transcripts it wrote to target/transcripts/. Needs JDK 25 and Maven. +set -euo pipefail +cd "$(dirname "$0")/.." +mvn -B -q test +for f in target/transcripts/*.txt; do + echo "##### $f" + cat "$f" + echo +done diff --git a/flush-ordering/src/main/java/com/ankurm/flush/Account.java b/flush-ordering/src/main/java/com/ankurm/flush/Account.java new file mode 100644 index 0000000..a648945 --- /dev/null +++ b/flush-ordering/src/main/java/com/ankurm/flush/Account.java @@ -0,0 +1,26 @@ +package com.ankurm.flush; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +/** A table with a unique column, for the delete-then-reinsert scenarios. */ +@Entity +@Table(name = "account") +public class Account { + + @Id + public Long id; + + @Column(name = "email", unique = true) + public String email; + + public Account() { + } + + public Account(Long id, String email) { + this.id = id; + this.email = email; + } +} diff --git a/flush-ordering/src/main/java/com/ankurm/flush/Author.java b/flush-ordering/src/main/java/com/ankurm/flush/Author.java new file mode 100644 index 0000000..e79dbd5 --- /dev/null +++ b/flush-ordering/src/main/java/com/ankurm/flush/Author.java @@ -0,0 +1,24 @@ +package com.ankurm.flush; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +/** The parent row. Id is assigned by the caller so the SQL is easy to read. */ +@Entity +@Table(name = "author") +public class Author { + + @Id + public Long id; + + public String name; + + public Author() { + } + + public Author(Long id, String name) { + this.id = id; + this.name = name; + } +} diff --git a/flush-ordering/src/main/java/com/ankurm/flush/Comment.java b/flush-ordering/src/main/java/com/ankurm/flush/Comment.java new file mode 100644 index 0000000..256a8d9 --- /dev/null +++ b/flush-ordering/src/main/java/com/ankurm/flush/Comment.java @@ -0,0 +1,30 @@ +package com.ankurm.flush; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; + +/** Like Post, but the foreign key is NOT NULL, so Hibernate cannot insert it as null and fix it up later. */ +@Entity +@Table(name = "comment") +public class Comment { + + @Id + public Long id; + + public String body; + + @ManyToOne + @jakarta.persistence.JoinColumn(nullable = false) + public Author author; + + public Comment() { + } + + public Comment(Long id, String body, Author author) { + this.id = id; + this.body = body; + this.author = author; + } +} diff --git a/flush-ordering/src/main/java/com/ankurm/flush/Post.java b/flush-ordering/src/main/java/com/ankurm/flush/Post.java new file mode 100644 index 0000000..cc09232 --- /dev/null +++ b/flush-ordering/src/main/java/com/ankurm/flush/Post.java @@ -0,0 +1,29 @@ +package com.ankurm.flush; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; + +/** The child row: post.author_id is a foreign key to author.id. */ +@Entity +@Table(name = "post") +public class Post { + + @Id + public Long id; + + public String title; + + @ManyToOne + public Author author; + + public Post() { + } + + public Post(Long id, String title, Author author) { + this.id = id; + this.title = title; + this.author = author; + } +} diff --git a/flush-ordering/src/test/java/com/ankurm/flush/FlushOrderingTest.java b/flush-ordering/src/test/java/com/ankurm/flush/FlushOrderingTest.java new file mode 100644 index 0000000..8510a00 --- /dev/null +++ b/flush-ordering/src/test/java/com/ankurm/flush/FlushOrderingTest.java @@ -0,0 +1,200 @@ +package com.ankurm.flush; + +import jakarta.persistence.PersistenceException; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Each test runs the same unit of work twice, once per flush queue, and writes the SQL that really + * reached JDBC to target/transcripts/. The assertions pin the same facts the post quotes. + */ +class FlushOrderingTest { + + private static final String PLAIN_SELECTS = "select "; + + /** SQL of the flush only: lookups Hibernate does while persisting/removing are left out of the transcript. */ + private static List writes(List all) { + return all.stream().filter(s -> !s.startsWith(PLAIN_SELECTS)).toList(); + } + + private static String rootMessage(Throwable t) { + while (t.getCause() != null) { + t = t.getCause(); + } + String m = String.valueOf(t.getMessage()); + int cut = m.indexOf("; SQL statement"); + return t.getClass().getName() + ": " + (cut > 0 ? m.substring(0, cut) : m).replaceAll("\\s+", " "); + } + + /** Runs setup, forgets its SQL, runs the work, and returns the write statements (or the failure). */ + private static List run(String queue, Map extra, + Consumer setup, + Consumer work, + Transcript t, String label) { + try (Lab lab = new Lab(queue, extra)) { + lab.sf.runInTransaction(setup); + lab.drain(); + try { + lab.sf.runInTransaction(work); + List sql = writes(lab.drain()); + t.sql(label + " -> committed", sql); + return sql; + } catch (RuntimeException e) { + List sql = writes(lab.drain()); + t.sql(label + " -> FAILED", sql); + t.line(" %s", rootMessage(e)); + throw e; + } + } + } + + private static List deletes(List sql) { + return sql.stream().filter(s -> s.startsWith("delete")).toList(); + } + + private static void none(jakarta.persistence.EntityManager em) { + } + + @Test + void insertOrder() { + try (Transcript t = new Transcript("01-insert-order")) { + Consumer work = em -> { + Author a = new Author(1L, "Ada"); + em.persist(new Post(10L, "Hello", a)); // child persisted first, parent second + em.persist(a); + }; + List legacy = run("legacy", Map.of(), FlushOrderingTest::none, work, t, "legacy"); + t.line(""); + List graph = run("graph", Map.of(), FlushOrderingTest::none, work, t, "graph"); + t.line(""); + List dflt = run(null, Map.of(), FlushOrderingTest::none, work, t, "no setting at all"); + assertTrue(legacy.get(0).startsWith("insert into post")); + assertTrue(graph.get(0).startsWith("insert into author")); + assertEquals(graph, dflt); + assertNotEquals(legacy, graph); + } + } + + @Test + void deleteOrder() { + try (Transcript t = new Transcript("02-delete-order")) { + Consumer setup = em -> { + Author a = new Author(1L, "Ada"); + em.persist(a); + em.persist(new Post(10L, "Hello", a)); + }; + Consumer work = em -> { + em.remove(em.find(Author.class, 1L)); // parent removed first + em.remove(em.find(Post.class, 10L)); + }; + List legacy = run("legacy", Map.of(), setup, work, t, "legacy"); + t.line(""); + List graph = run("graph", Map.of(), setup, work, t, "graph"); + assertEquals("delete from author where id=? [1]", deletes(legacy).get(0)); + assertEquals("delete from post where id=? [10]", deletes(graph).get(0)); + } + } + + @Test + void uniqueDeleteThenReinsert() { + try (Transcript t = new Transcript("03-unique-delete-reinsert")) { + Consumer setup = em -> em.persist(new Account(1L, "a@x.com")); + Consumer work = em -> { + em.remove(em.find(Account.class, 1L)); + em.persist(new Account(2L, "a@x.com")); // same unique email, new row + }; + assertThrows(PersistenceException.class, () -> run("legacy", Map.of(), setup, work, t, "legacy")); + t.line(""); + List graph = run("graph", Map.of(), setup, work, t, "graph"); + assertTrue(graph.get(0).startsWith("delete from account")); + } + } + + @Test + void uniqueSwap() { + try (Transcript t = new Transcript("04-unique-swap")) { + Consumer setup = em -> { + em.persist(new Account(1L, "a@x.com")); + em.persist(new Account(2L, "b@x.com")); + }; + Consumer work = em -> { + em.find(Account.class, 1L).email = "b@x.com"; + em.find(Account.class, 2L).email = "a@x.com"; + }; + assertThrows(PersistenceException.class, () -> run("legacy", Map.of(), setup, work, t, "legacy")); + t.line(""); + List graph = run("graph", Map.of(), setup, work, t, "graph"); + assertEquals(3, graph.stream().filter(s -> s.startsWith("update account")).count()); + t.line(""); + assertThrows(PersistenceException.class, () -> run("graph", + Map.of("hibernate.flush.plan.uniquekey.order", "false"), setup, work, t, + "graph with hibernate.flush.plan.uniquekey.order=false")); + } + } + + @Test + void notNullForeignKeyIsNotRescued() { + try (Transcript t = new Transcript("05-not-null-not-rescued")) { + for (String queue : new String[]{"legacy", "graph"}) { + try (Lab lab = new Lab(queue)) { + Author a = new Author(1L, "Ada"); + RuntimeException e = assertThrows(RuntimeException.class, () -> lab.sf.runInTransaction(em -> { + em.persist(new Comment(10L, "Hi", a)); // Comment.author is NOT NULL, Ada is not persisted + em.persist(a); + })); + t.line("%s: %s", queue, e.getClass().getName()); + t.line(" %s", rootMessage(e)); + } + } + } + } + + @Test + void batching() { + try (Transcript t = new Transcript("06-batching")) { + Map batch = Map.of("hibernate.jdbc.batch_size", "10"); + Consumer work = em -> { + for (long i = 1; i <= 2; i++) { + Author a = new Author(i, "A" + i); + em.persist(a); + em.persist(new Post(10 + i, "P" + i, a)); + } + }; + List legacy = null; + List graph = null; + for (String queue : new String[]{"legacy", "graph"}) { + try (Lab lab = new Lab(queue, batch)) { + lab.sf.runInTransaction(work); + List sql = lab.drain().stream().filter(s -> !s.startsWith(PLAIN_SELECTS)).toList(); + t.sql(queue + " with hibernate.jdbc.batch_size=10", sql); + t.line(""); + if (queue.equals("legacy")) legacy = sql; else graph = sql; + } + } + assertEquals(4, legacy.stream().filter(s -> s.startsWith("-- executeBatch")).count()); + assertEquals(2, graph.stream().filter(s -> s.startsWith("-- executeBatch")).count()); + } + } + + @Test + void settingValues() { + try (Transcript t = new Transcript("07-setting-values")) { + for (String value : new String[]{"GRAPH", "Legacy", "bogus"}) { + try (Lab lab = new Lab(value)) { + t.line("hibernate.flush.queue.type=%s -> SessionFactory built", value); + } catch (RuntimeException e) { + t.line("hibernate.flush.queue.type=%s -> %s", value, rootMessage(e)); + assertEquals("bogus", value); + } + } + } + } +} diff --git a/flush-ordering/src/test/java/com/ankurm/flush/Lab.java b/flush-ordering/src/test/java/com/ankurm/flush/Lab.java new file mode 100644 index 0000000..b0dd4a2 --- /dev/null +++ b/flush-ordering/src/test/java/com/ankurm/flush/Lab.java @@ -0,0 +1,44 @@ +package com.ankurm.flush; + +import org.hibernate.SessionFactory; +import org.hibernate.jpa.HibernatePersistenceConfiguration; + +import java.util.List; +import java.util.UUID; + +/** Boots a Hibernate 8 SessionFactory on H2 with a chosen flush queue and records the SQL. */ +final class Lab implements AutoCloseable { + + final SessionFactory sf; + + Lab(String queueType) { + this(queueType, java.util.Map.of()); + } + + Lab(String queueType, java.util.Map extra) { + String id = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + SqlRecorder.URL = "jdbc:h2:mem:lab" + id + ";DB_CLOSE_DELAY=-1"; + var cfg = new HibernatePersistenceConfiguration("lab") + .managedClasses(Author.class, Post.class, Comment.class, Account.class) + .property("hibernate.connection.provider_class", SqlRecorder.class.getName()) + .property("jakarta.persistence.schema-generation.database.action", "create"); + if (queueType != null) { + cfg.property("hibernate.flush.queue.type", queueType); + } + extra.forEach(cfg::property); + this.sf = cfg.createEntityManagerFactory(); + SqlRecorder.LOG.clear(); + } + + /** SQL executed since the last call, then forgets it. */ + List drain() { + List copy = List.copyOf(SqlRecorder.LOG); + SqlRecorder.LOG.clear(); + return copy; + } + + @Override + public void close() { + sf.close(); + } +} diff --git a/flush-ordering/src/test/java/com/ankurm/flush/SqlRecorder.java b/flush-ordering/src/test/java/com/ankurm/flush/SqlRecorder.java new file mode 100644 index 0000000..c6b5cbc --- /dev/null +++ b/flush-ordering/src/test/java/com/ankurm/flush/SqlRecorder.java @@ -0,0 +1,95 @@ +package com.ankurm.flush; + +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * A ConnectionProvider that wraps every PreparedStatement in a proxy and records the SQL together with + * the bound parameter values at the moment the statement is executed. That is what lets a transcript + * say "insert into post ... [10, Hello, 1]" instead of a row of question marks. + */ +public class SqlRecorder implements ConnectionProvider { + + public static final List LOG = Collections.synchronizedList(new ArrayList<>()); + + /** Set by Lab before the SessionFactory is built; Hibernate needs a public no-arg constructor. */ + public static volatile String URL; + + public SqlRecorder() { + } + + @Override + public Connection getConnection() throws SQLException { + Connection real = DriverManager.getConnection(URL, "sa", ""); + return (Connection) Proxy.newProxyInstance( + SqlRecorder.class.getClassLoader(), new Class[]{Connection.class}, + (proxy, method, args) -> { + Object result = invoke(real, method, args); + if (method.getName().equals("prepareStatement") && result instanceof PreparedStatement ps) { + return wrap(ps, (String) args[0]); + } + return result; + }); + } + + private static Object invoke(Object target, java.lang.reflect.Method m, Object[] args) throws Throwable { + try { + return m.invoke(target, args); + } catch (java.lang.reflect.InvocationTargetException e) { + throw e.getCause(); + } + } + + private static PreparedStatement wrap(PreparedStatement ps, String sql) { + Map params = new TreeMap<>(); + InvocationHandler h = (proxy, method, args) -> { + String n = method.getName(); + if (n.startsWith("set") && args != null && args.length >= 2 && args[0] instanceof Integer i) { + params.put(i, n.equals("setNull") ? "null" : args[1]); + } + if (n.equals("executeUpdate") || n.equals("addBatch") || n.equals("execute") || n.equals("executeQuery")) { + LOG.add(sql.replaceAll("\\s+", " ").trim() + " " + params.values()); + if (n.equals("addBatch")) { + params.clear(); + } + } + if (n.equals("executeBatch")) { + LOG.add("-- executeBatch()"); + } + return invoke(ps, method, args); + }; + return (PreparedStatement) Proxy.newProxyInstance( + SqlRecorder.class.getClassLoader(), new Class[]{PreparedStatement.class}, h); + } + + @Override + public void closeConnection(Connection conn) throws SQLException { + conn.close(); + } + + @Override + public boolean supportsAggressiveRelease() { + return false; + } + + @Override + public boolean isUnwrappableAs(Class unwrapType) { + return unwrapType.isAssignableFrom(SqlRecorder.class); + } + + @Override + public T unwrap(Class unwrapType) { + return unwrapType.cast(this); + } +} diff --git a/flush-ordering/src/test/java/com/ankurm/flush/Transcript.java b/flush-ordering/src/test/java/com/ankurm/flush/Transcript.java new file mode 100644 index 0000000..6addbf1 --- /dev/null +++ b/flush-ordering/src/test/java/com/ankurm/flush/Transcript.java @@ -0,0 +1,44 @@ +package com.ankurm.flush; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * Collects printed lines and writes them to target/transcripts/NN-name.txt. The blog post quotes these + * files verbatim, and the test that writes each one asserts the same behaviour, so a claim that stops + * being true fails the build. + */ +final class Transcript implements AutoCloseable { + + private final Path file; + private final List lines = new ArrayList<>(); + + Transcript(String name) { + this.file = Path.of("target", "transcripts", name + ".txt"); + } + + void line(String fmt, Object... args) { + lines.add(args.length == 0 ? fmt : String.format(fmt, args)); + } + + void sql(String label, List statements) { + long n = statements.stream().filter(x -> !x.startsWith("--")).count(); + line("%s (%d statement%s)", label, n, n == 1 ? "" : "s"); + for (String s : statements) { + line(" %s", s); + } + } + + @Override + public void close() { + try { + Files.createDirectories(file.getParent()); + Files.write(file, lines); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +}