work) {
+ tx(s -> {
+ work.accept(s);
+ return null;
+ });
+ }
+
+ @Override
+ public void close() {
+ if (sf.isOpen()) {
+ sf.close();
+ }
+ }
+}
diff --git a/n-plus-one-guard/src/main/java/com/ankurm/nplusone/MaxSelects.java b/n-plus-one-guard/src/main/java/com/ankurm/nplusone/MaxSelects.java
new file mode 100644
index 0000000..456f70b
--- /dev/null
+++ b/n-plus-one-guard/src/main/java/com/ankurm/nplusone/MaxSelects.java
@@ -0,0 +1,19 @@
+package com.ankurm.nplusone;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+/**
+ * Query budget for one test: the test fails if it sends more than {@link #value()} SELECT statements.
+ * Put it on a method, or on the class to apply the same budget to every test in it.
+ */
+@Target({ ElementType.METHOD, ElementType.TYPE })
+@Retention(RetentionPolicy.RUNTIME)
+@ExtendWith(QueryGuardExtension.class)
+public @interface MaxSelects {
+
+ int value();
+}
diff --git a/n-plus-one-guard/src/main/java/com/ankurm/nplusone/QueryGuard.java b/n-plus-one-guard/src/main/java/com/ankurm/nplusone/QueryGuard.java
new file mode 100644
index 0000000..e084a00
--- /dev/null
+++ b/n-plus-one-guard/src/main/java/com/ankurm/nplusone/QueryGuard.java
@@ -0,0 +1,95 @@
+package com.ankurm.nplusone;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.sql.DataSource;
+import net.ttddyy.dsproxy.QueryCount;
+import net.ttddyy.dsproxy.QueryCountHolder;
+import net.ttddyy.dsproxy.QueryInfo;
+import net.ttddyy.dsproxy.listener.QueryExecutionListener;
+import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
+import org.opentest4j.AssertionFailedError;
+
+/**
+ * Counts every statement that reaches the JDBC driver, whoever sent it.
+ *
+ * {@link #wrap(DataSource)} puts datasource-proxy between Hibernate and the real DataSource.
+ * datasource-proxy keeps per-type counters (select / insert / update / delete) in
+ * {@link QueryCountHolder}; a small listener additionally remembers the SQL text so a failed
+ * assertion can print the statements that broke the budget. Counters are per thread: the code
+ * under test and the assertion must run on the same thread.
+ */
+public final class QueryGuard {
+
+ static final String DATASOURCE_NAME = "guarded";
+
+ private static final ThreadLocal> SQL = ThreadLocal.withInitial(ArrayList::new);
+
+ private QueryGuard() {
+ }
+
+ /** Wraps a DataSource so every statement is counted and recorded. */
+ public static DataSource wrap(DataSource real) {
+ return ProxyDataSourceBuilder.create(real)
+ .name(DATASOURCE_NAME)
+ .countQuery()
+ .listener(new QueryExecutionListener() {
+ @Override
+ public void beforeQuery(net.ttddyy.dsproxy.ExecutionInfo execInfo, List queryInfoList) {
+ }
+
+ @Override
+ public void afterQuery(net.ttddyy.dsproxy.ExecutionInfo execInfo, List queryInfoList) {
+ for (QueryInfo q : queryInfoList) {
+ SQL.get().add(q.getQuery().replaceAll("\\s+", " ").trim());
+ }
+ }
+ })
+ .build();
+ }
+
+ /** Zeroes the counters and the SQL log for the current thread. */
+ public static void reset() {
+ QueryCountHolder.clear();
+ SQL.get().clear();
+ }
+
+ public static QueryCount counts() {
+ QueryCount c = QueryCountHolder.get(DATASOURCE_NAME);
+ return c != null ? c : new QueryCount();
+ }
+
+ public static long selects() {
+ return counts().getSelect();
+ }
+
+ public static List sql() {
+ return List.copyOf(SQL.get());
+ }
+
+ /** Runs the action from a clean slate and returns the SELECT count it caused. */
+ public static long countSelects(Runnable action) {
+ reset();
+ action.run();
+ return selects();
+ }
+
+ /** Fails with the full statement list when the current thread has sent more than {@code max} SELECTs. */
+ public static void assertMaxSelects(long max, String what) {
+ long actual = selects();
+ if (actual > max) {
+ throw new AssertionFailedError(message(max, actual, what));
+ }
+ }
+
+ static String message(long max, long actual, String what) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(what).append(": expected at most ").append(max).append(" SELECT statement(s) but ")
+ .append(actual).append(" were sent.");
+ int i = 1;
+ for (String s : SQL.get()) {
+ sb.append(System.lineSeparator()).append(" ").append(i++).append(") ").append(s);
+ }
+ return sb.toString();
+ }
+}
diff --git a/n-plus-one-guard/src/main/java/com/ankurm/nplusone/QueryGuardExtension.java b/n-plus-one-guard/src/main/java/com/ankurm/nplusone/QueryGuardExtension.java
new file mode 100644
index 0000000..64b7b53
--- /dev/null
+++ b/n-plus-one-guard/src/main/java/com/ankurm/nplusone/QueryGuardExtension.java
@@ -0,0 +1,31 @@
+package com.ankurm.nplusone;
+
+import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
+import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.platform.commons.support.AnnotationSupport;
+
+/**
+ * Enforces {@link MaxSelects}.
+ *
+ * The counters are reset in {@code BeforeTestExecutionCallback}, which runs after
+ * {@code @BeforeEach} methods, so seeding done there is not counted against the test. The check
+ * runs in {@code AfterTestExecutionCallback}, before {@code @AfterEach}.
+ */
+public class QueryGuardExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
+
+ @Override
+ public void beforeTestExecution(ExtensionContext ctx) {
+ QueryGuard.reset();
+ }
+
+ @Override
+ public void afterTestExecution(ExtensionContext ctx) {
+ MaxSelects budget = AnnotationSupport.findAnnotation(ctx.getTestMethod(), MaxSelects.class)
+ .or(() -> AnnotationSupport.findAnnotation(ctx.getTestClass(), MaxSelects.class))
+ .orElse(null);
+ if (budget != null) {
+ QueryGuard.assertMaxSelects(budget.value(), ctx.getDisplayName());
+ }
+ }
+}
diff --git a/n-plus-one-guard/src/test/java/com/ankurm/nplusone/BrokenFixture.java b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/BrokenFixture.java
new file mode 100644
index 0000000..4881001
--- /dev/null
+++ b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/BrokenFixture.java
@@ -0,0 +1,35 @@
+package com.ankurm.nplusone;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/**
+ * A deliberately regressed test: it is NOT picked up by surefire (name does not end in Test).
+ * {@link T03_GuardTest} runs it through the JUnit Platform and records the failure message.
+ */
+class BrokenFixture {
+
+ static Db db;
+
+ @BeforeAll
+ static void open() {
+ db = Db.open();
+ db.seed(10, 3);
+ }
+
+ @AfterAll
+ static void close() {
+ db.close();
+ }
+
+ @Test
+ @MaxSelects(2)
+ void listAuthorsWithBookCount() {
+ db.txv(s -> {
+ for (Author a : s.createQuery("from Author", Author.class).getResultList()) {
+ a.getBooks().size();
+ }
+ });
+ }
+}
diff --git a/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T01_ReproduceTest.java b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T01_ReproduceTest.java
new file mode 100644
index 0000000..613427a
--- /dev/null
+++ b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T01_ReproduceTest.java
@@ -0,0 +1,73 @@
+package com.ankurm.nplusone;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import org.hibernate.stat.Statistics;
+import org.junit.jupiter.api.Test;
+
+/** Reproduces both flavours of N+1 and shows what each counter reports. */
+class T01_ReproduceTest {
+
+ @Test
+ void collectionNPlusOne() {
+ Transcript t = new Transcript("01-n-plus-one", "N+1 on a lazy collection: 10 authors, 3 books each");
+ try (Db db = Db.open()) {
+ db.seed(10, 3);
+ Statistics stats = db.sf().getStatistics();
+
+ int[] books = {0};
+ db.txv(s -> {
+ List authors = s.createQuery("from Author", Author.class).getResultList();
+ for (Author a : authors) {
+ books[0] += a.getBooks().size();
+ }
+ });
+
+ t.heading("Code: one HQL query, then a.getBooks().size() for every author");
+ t.line("books counted by the loop : " + books[0]);
+ t.line("datasource-proxy SELECT count : " + QueryGuard.selects());
+ t.line("Hibernate prepareStatementCount : " + stats.getPrepareStatementCount());
+ t.line("Hibernate queryExecutionCount : " + stats.getQueryExecutionCount());
+ t.line("Hibernate collectionFetchCount : " + stats.getCollectionFetchCount());
+ t.line("Hibernate collectionLoadCount : " + stats.getCollectionLoadCount());
+ t.heading("The statements, in order");
+ t.sql(QueryGuard.sql());
+
+ assertThat(books[0]).isEqualTo(30);
+ assertThat(QueryGuard.selects()).isEqualTo(11);
+ assertThat(stats.getPrepareStatementCount()).isEqualTo(11);
+ // The trap: HQL executions are 1 because lazy loads are not "queries" to Hibernate.
+ assertThat(stats.getQueryExecutionCount()).isEqualTo(1);
+ assertThat(stats.getCollectionFetchCount()).isEqualTo(10);
+ }
+ t.write();
+ }
+
+ @Test
+ void toOneNPlusOne() {
+ Transcript t = new Transcript("02-n-plus-one-to-one", "N+1 on a lazy @ManyToOne: 30 books, 10 distinct authors");
+ try (Db db = Db.open()) {
+ db.seed(10, 3);
+ Statistics stats = db.sf().getStatistics();
+
+ db.txv(s -> {
+ List all = s.createQuery("from Book", Book.class).getResultList();
+ for (Book b : all) {
+ b.getAuthor().getName();
+ }
+ });
+
+ t.heading("Code: one HQL query for 30 books, then book.getAuthor().getName() for every book");
+ t.line("datasource-proxy SELECT count : " + QueryGuard.selects());
+ t.line("Hibernate entityFetchCount : " + stats.getEntityFetchCount());
+ t.heading("The statements, in order");
+ t.sql(QueryGuard.sql());
+
+ // 30 rows, but only 10 distinct authors: the persistence context loads each author once.
+ assertThat(QueryGuard.selects()).isEqualTo(11);
+ assertThat(stats.getEntityFetchCount()).isEqualTo(10);
+ }
+ t.write();
+ }
+}
diff --git a/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T02_FixesTest.java b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T02_FixesTest.java
new file mode 100644
index 0000000..b151b74
--- /dev/null
+++ b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T02_FixesTest.java
@@ -0,0 +1,86 @@
+package com.ankurm.nplusone;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
+import org.hibernate.Session;
+import org.junit.jupiter.api.Test;
+
+/** The same "list every author with a book count" job, written five ways, with the SELECT count of each. */
+class T02_FixesTest {
+
+ private static final String HEADING = "SELECT statements for 10 authors x 3 books, same result every time (30 books)";
+
+ @Test
+ void fixesCompared() {
+ Transcript t = new Transcript("03-fixes", "Five ways to load 10 authors with their books");
+ Map counts = new LinkedHashMap<>();
+ try (Db db = Db.open()) {
+ db.seed(10, 3);
+
+ run(db, t, counts, "naive loop (lazy collection per author)", s -> total(s.createQuery("from Author", Author.class).getResultList()));
+ run(db, t, counts, "join fetch", s -> total(s.createQuery("select a from Author a join fetch a.books", Author.class).getResultList()));
+ run(db, t, counts, "entity graph (Author.withBooks)", s -> total(s.createQuery("from Author", Author.class)
+ .setHint("jakarta.persistence.fetchgraph", s.getEntityGraph("Author.withBooks")).getResultList()));
+ run(db, t, counts, "batch fetching, size 5 (session.setFetchBatchSize)", s -> {
+ s.setFetchBatchSize(5);
+ return total(s.createQuery("from Author", Author.class).getResultList());
+ });
+ run(db, t, counts, "DTO projection (no entities)", s -> s.createQuery(
+ "select count(b) from Book b group by b.author.id", Long.class).getResultList().stream().mapToInt(Long::intValue).sum());
+ }
+ t.heading(HEADING);
+ counts.forEach((k, v) -> t.line(String.format("%-52s %d", k, v)));
+ t.write();
+
+ assertThat(counts.values()).containsExactly(11L, 1L, 1L, 3L, 1L);
+ }
+
+ private static int total(List authors) {
+ int n = 0;
+ for (Author a : authors) {
+ n += a.getBooks().size();
+ }
+ return n;
+ }
+
+ private static void run(Db db, Transcript t, Map counts, String label, java.util.function.Function job) {
+ QueryGuard.reset();
+ int books = db.tx(job);
+ assertThat(books).as(label).isEqualTo(30);
+ counts.put(label, QueryGuard.selects());
+ t.heading(label);
+ t.sql(QueryGuard.sql());
+ }
+
+ /**
+ * join fetch on a collection + setMaxResults. Older Hibernate versions paged this in memory (warning HHH90003004);
+ * this test pins what 7.4 does: the limit is applied in SQL, to the owning side, inside a subquery.
+ */
+ @Test
+ void joinFetchPagination() {
+ Transcript t = new Transcript("04-join-fetch-pagination", "join fetch on a collection + setMaxResults(3), 10 authors x 3 books");
+ try (Db db = Db.open()) {
+ db.seed(10, 3);
+ QueryGuard.reset();
+ List page = db.tx(s -> {
+ List r = s.createQuery("select a from Author a join fetch a.books order by a.id", Author.class)
+ .setMaxResults(3).getResultList();
+ r.forEach(a -> a.getBooks().size());
+ return r;
+ });
+ int books = page.stream().mapToInt(a -> a.getBooks().size()).sum();
+ t.line("authors returned: " + page.size() + ", books loaded: " + books);
+ t.line("SELECT statements: " + QueryGuard.selects());
+ t.sql(QueryGuard.sql());
+ assertThat(page).hasSize(3);
+ assertThat(books).isEqualTo(9);
+ assertThat(QueryGuard.selects()).isEqualTo(1);
+ assertThat(QueryGuard.sql().get(0)).contains("fetch first");
+ }
+ t.write();
+ }
+}
diff --git a/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T03_GuardTest.java b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T03_GuardTest.java
new file mode 100644
index 0000000..4839af8
--- /dev/null
+++ b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/T03_GuardTest.java
@@ -0,0 +1,51 @@
+package com.ankurm.nplusone;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.platform.testkit.engine.EngineTestKit;
+
+/** The guard itself: a passing budget, and the failure message a regressed test produces. */
+class T03_GuardTest {
+
+ private Db db;
+
+ @BeforeEach
+ void seed() {
+ // Db.seed() clears every counter when it finishes, so the INSERTs never count against a budget.
+ db = Db.open();
+ db.seed(10, 3);
+ }
+
+ @org.junit.jupiter.api.AfterEach
+ void close() {
+ db.close();
+ }
+
+ @Test
+ @MaxSelects(1)
+ void joinFetchStaysWithinBudget() {
+ db.txv(s -> s.createQuery("select a from Author a join fetch a.books", Author.class).getResultList()
+ .forEach(a -> a.getBooks().size()));
+ }
+
+ @Test
+ void regressedTestFailsWithTheStatementList() {
+ var results = EngineTestKit.engine("junit-jupiter").selectors(selectClass(BrokenFixture.class)).execute();
+ var failures = results.testEvents().failed().stream().toList();
+ assertThat(failures).hasSize(1);
+ String message = failures.get(0).getRequiredPayload(org.junit.platform.engine.TestExecutionResult.class)
+ .getThrowable().orElseThrow().getMessage();
+
+ Transcript t = new Transcript("05-guard-failure", "What the guard prints when a test regresses (BrokenFixture, @MaxSelects(2))");
+ t.heading("Failure message");
+ message.lines().forEach(t::line);
+ t.write();
+
+ assertThat(message).contains("expected at most 2 SELECT statement(s) but 11 were sent.");
+ assertThat(message).contains("1) select a1_0.id,a1_0.name from Author a1_0");
+ assertThat(message).contains("11) select b1_0.author_id");
+ }
+}
diff --git a/n-plus-one-guard/src/test/java/com/ankurm/nplusone/Transcript.java b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/Transcript.java
new file mode 100644
index 0000000..7bd5502
--- /dev/null
+++ b/n-plus-one-guard/src/test/java/com/ankurm/nplusone/Transcript.java
@@ -0,0 +1,48 @@
+package com.ankurm.nplusone;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Collects what a test observed and writes output/NN-name.txt; the tests assert the same facts. */
+final class Transcript {
+
+ private final List lines = new ArrayList<>();
+ private final Path file;
+
+ Transcript(String name, String title) {
+ this.file = Path.of("output", name + ".txt");
+ line("# " + title);
+ line("# Hibernate ORM " + System.getProperty("h.version", "?") + ", datasource-proxy "
+ + System.getProperty("dsp.version", "?") + ", H2, JDK " + Runtime.version().feature());
+ }
+
+ Transcript line(String s) {
+ lines.add(s);
+ return this;
+ }
+
+ Transcript heading(String s) {
+ line("");
+ return line("== " + s);
+ }
+
+ Transcript sql(List sql) {
+ for (String s : sql) {
+ line(" sql> " + s);
+ }
+ return this;
+ }
+
+ void write() {
+ try {
+ Files.createDirectories(file.getParent());
+ Files.write(file, lines);
+ }
+ catch (IOException ex) {
+ throw new IllegalStateException(ex);
+ }
+ }
+}