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
+38
View File
@@ -0,0 +1,38 @@
# n-plus-one-guard
Companion module for the ankurm.com article **Catch N+1 Queries Automatically: Hibernate Statistics, datasource-proxy and a JUnit Guard**.
Every statement count and SQL line in the article comes from a test here; each test writes what it observed to `output/` and asserts the same facts.
Plain Hibernate on an in-memory H2: no Spring, no Docker.
## Versions
| Component | Version | Notes |
|---|---|---|
| Hibernate ORM | `7.4.16.Final` | newest 7.x GA in `maven-metadata.xml` on 2026-11-17 (`8.0.0.CR1` is listed after it but is not GA) |
| datasource-proxy | `1.11.1` | `net.ttddyy:datasource-proxy` |
| JUnit | `6.1.3` | Jupiter, plus `junit-platform-testkit` to run the deliberately failing fixture |
| H2 / AssertJ | `2.4.240` / `3.27.7` | |
| Java | `25` (Temurin 25.0.5+8) | |
## Run
```bash
./scripts/run-all.sh # or: mvn clean test
```
## What is where
| File | Role |
|---|---|
| `Author`, `Book` | The entities: lazy `@OneToMany` and lazy `@ManyToOne`; `Author.withBooks` is the entity graph |
| `QueryGuard` | Wraps a `DataSource` with datasource-proxy, counts SELECT/INSERT/UPDATE/DELETE per thread and remembers the SQL |
| `@MaxSelects` + `QueryGuardExtension` | The JUnit extension: a per-test (or per-class) SELECT budget; copy these two files and `QueryGuard` into your own project |
| `Db` | Plain Hibernate bootstrap with the guarded DataSource and `hibernate.generate_statistics=true` |
| Test | Output | Question it answers |
|---|---|---|
| `T01_ReproduceTest` | `output/01-n-plus-one.txt`, `output/02-n-plus-one-to-one.txt` | How many statements does N+1 send, and what do Hibernate Statistics and datasource-proxy each report for it? |
| `T02_FixesTest` | `output/03-fixes.txt`, `output/04-join-fetch-pagination.txt` | What does each fix send, and what does `join fetch` + `setMaxResults` do in Hibernate 7.4? |
| `T03_GuardTest` | `output/05-guard-failure.txt` | What does the guard print when a test regresses? (runs `BrokenFixture` through the JUnit Platform) |
`BrokenFixture` is deliberately failing and is not run by Surefire (its name does not match Surefire's patterns); only `T03_GuardTest` runs it.