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 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b3obqqePfZ9m2Jk5Ub
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<String> writes(List<String> 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<String> run(String queue, Map<String, String> extra,
|
||||
Consumer<jakarta.persistence.EntityManager> setup,
|
||||
Consumer<jakarta.persistence.EntityManager> work,
|
||||
Transcript t, String label) {
|
||||
try (Lab lab = new Lab(queue, extra)) {
|
||||
lab.sf.runInTransaction(setup);
|
||||
lab.drain();
|
||||
try {
|
||||
lab.sf.runInTransaction(work);
|
||||
List<String> sql = writes(lab.drain());
|
||||
t.sql(label + " -> committed", sql);
|
||||
return sql;
|
||||
} catch (RuntimeException e) {
|
||||
List<String> sql = writes(lab.drain());
|
||||
t.sql(label + " -> FAILED", sql);
|
||||
t.line(" %s", rootMessage(e));
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> deletes(List<String> 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<jakarta.persistence.EntityManager> work = em -> {
|
||||
Author a = new Author(1L, "Ada");
|
||||
em.persist(new Post(10L, "Hello", a)); // child persisted first, parent second
|
||||
em.persist(a);
|
||||
};
|
||||
List<String> legacy = run("legacy", Map.of(), FlushOrderingTest::none, work, t, "legacy");
|
||||
t.line("");
|
||||
List<String> graph = run("graph", Map.of(), FlushOrderingTest::none, work, t, "graph");
|
||||
t.line("");
|
||||
List<String> 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<jakarta.persistence.EntityManager> setup = em -> {
|
||||
Author a = new Author(1L, "Ada");
|
||||
em.persist(a);
|
||||
em.persist(new Post(10L, "Hello", a));
|
||||
};
|
||||
Consumer<jakarta.persistence.EntityManager> work = em -> {
|
||||
em.remove(em.find(Author.class, 1L)); // parent removed first
|
||||
em.remove(em.find(Post.class, 10L));
|
||||
};
|
||||
List<String> legacy = run("legacy", Map.of(), setup, work, t, "legacy");
|
||||
t.line("");
|
||||
List<String> 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<jakarta.persistence.EntityManager> setup = em -> em.persist(new Account(1L, "[email protected]"));
|
||||
Consumer<jakarta.persistence.EntityManager> work = em -> {
|
||||
em.remove(em.find(Account.class, 1L));
|
||||
em.persist(new Account(2L, "[email protected]")); // same unique email, new row
|
||||
};
|
||||
assertThrows(PersistenceException.class, () -> run("legacy", Map.of(), setup, work, t, "legacy"));
|
||||
t.line("");
|
||||
List<String> 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<jakarta.persistence.EntityManager> setup = em -> {
|
||||
em.persist(new Account(1L, "[email protected]"));
|
||||
em.persist(new Account(2L, "[email protected]"));
|
||||
};
|
||||
Consumer<jakarta.persistence.EntityManager> work = em -> {
|
||||
em.find(Account.class, 1L).email = "[email protected]";
|
||||
em.find(Account.class, 2L).email = "[email protected]";
|
||||
};
|
||||
assertThrows(PersistenceException.class, () -> run("legacy", Map.of(), setup, work, t, "legacy"));
|
||||
t.line("");
|
||||
List<String> 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<String, String> batch = Map.of("hibernate.jdbc.batch_size", "10");
|
||||
Consumer<jakarta.persistence.EntityManager> 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<String> legacy = null;
|
||||
List<String> graph = null;
|
||||
for (String queue : new String[]{"legacy", "graph"}) {
|
||||
try (Lab lab = new Lab(queue, batch)) {
|
||||
lab.sf.runInTransaction(work);
|
||||
List<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> 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<String> drain() {
|
||||
List<String> copy = List.copyOf(SqlRecorder.LOG);
|
||||
SqlRecorder.LOG.clear();
|
||||
return copy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
sf.close();
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<Integer, Object> 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> T unwrap(Class<T> unwrapType) {
|
||||
return unwrapType.cast(this);
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user