Add n-plus-one-guard module: detecting N+1 with Hibernate Statistics vs datasource-proxy, five fixes with statement counts, and a JUnit 6 @MaxSelects guard (Hibernate 7.4.16.Final, datasource-proxy 1.11.1)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6R1spapM7nBteaqeo
This commit is contained in:
asmhatre
2026-11-17 00:48:25 +05:30
co-authored by Claude Sonnet 5.5
parent eab5461d86
commit 0db721805b
20 changed files with 851 additions and 0 deletions
@@ -0,0 +1,89 @@
package com.ankurm.nplusone;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import org.h2.jdbcx.JdbcDataSource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
/**
* Plain Hibernate bootstrap on an in-memory H2, with the DataSource wrapped by {@link QueryGuard}
* and Hibernate's own statistics switched on, so both counters can be compared on the same code.
*/
public final class Db implements AutoCloseable {
private final SessionFactory sf;
private Db(SessionFactory sf) {
this.sf = sf;
}
public static Db open() {
JdbcDataSource h2 = new JdbcDataSource();
h2.setURL("jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1");
h2.setUser("sa");
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySetting("jakarta.persistence.nonJtaDataSource", QueryGuard.wrap(h2))
.applySetting("hibernate.hbm2ddl.auto", "create-drop")
.applySetting("hibernate.generate_statistics", "true")
.build();
MetadataSources sources = new MetadataSources(registry)
.addAnnotatedClass(Author.class)
.addAnnotatedClass(Book.class);
return new Db(sources.buildMetadata().buildSessionFactory());
}
public SessionFactory sf() {
return sf;
}
/** Inserts {@code authors} authors with {@code booksEach} books each, then clears every counter. */
public void seed(int authors, int booksEach) {
txv(s -> {
for (int a = 0; a < authors; a++) {
Author author = new Author("author-" + a);
for (int b = 0; b < booksEach; b++) {
author.addBook(new Book("book-" + a + "-" + b));
}
s.persist(author);
}
});
sf.getStatistics().clear();
QueryGuard.reset();
}
public <T> T tx(Function<Session, T> work) {
try (Session s = sf.openSession()) {
var t = s.beginTransaction();
try {
T r = work.apply(s);
t.commit();
return r;
}
catch (RuntimeException e) {
if (t.isActive()) {
t.rollback();
}
throw e;
}
}
}
public void txv(Consumer<Session> work) {
tx(s -> {
work.accept(s);
return null;
});
}
@Override
public void close() {
if (sf.isOpen()) {
sf.close();
}
}
}