Skip to main content

Catch N+1 Queries in Spring Boot Tests by Asserting the Query Count

A naive listing of 10 customers touched lazy orders and used 11 prepared statements and 10 collection fetches. @EntityGraph and JOIN FETCH each used 1 statement and 0 collection fetches.

Updated 9 min readMarkdown
Part of seriesBackend & APIs
Catch N+1 Queries in Spring Boot Tests by Asserting the Query Count

I seeded 10 customers with 3 orders each, listed them, and touched customer.getOrders().size() so a lazy collection would actually load. Then I asked Hibernate how many statements it prepared. Pasted from the run on 20 Nov 2026, 08:28 IST:

[n+1] naive list of 10 customers (touch orders) -> prepareStatements=11 queryExecutions=1 collectionFetches=10
[n+1] @EntityGraph list of 10 customers -> prepareStatements=1 queryExecutions=1 collectionFetches=0
[n+1] JOIN FETCH list of 10 customers -> prepareStatements=1 queryExecutions=1 collectionFetches=0

The naive path is the textbook N+1: one query for the customers, then one collection fetch per customer. @EntityGraph and JOIN FETCH each prepared one statement and fetched zero collections lazily. No detector library, no annotation from a third-party JAR. The counter is Hibernate's own Statistics, cleared immediately before the call.

The short version

  • Turn hibernate.generate_statistics on in the test profile, unwrap the SessionFactory, call stats.clear(), run the service method, then assert getPrepareStatementCount() (and, usefully, getCollectionFetchCount()).
  • Seed enough rows. With one customer, N+1 is two statements and looks like a normal find-plus-collection. With 10 customers it was 11 and 10.
  • @EntityGraph(attributePaths = "orders") and join fetch c.orders both brought the same listing down to 1 prepared statement in this run.
  • Statistics are process-wide, on the SessionFactory. If you forget clear(), this run already had 43 statements on the counter (seed inserts plus earlier tests) before a one-statement listing ran. A second naive listing without a clear moved the counter from 11 to 22. Two naive listings started in parallel after one clear also totalled 22. Do not run these tests concurrently.
flowchart LR
    A["findAll() customers<br/>1 statement"] --> B["for each customer:<br/>orders.size()"]
    B --> C["10 lazy collection fetches"]
    C --> D["total: 11 prepares"]
    E["@EntityGraph or JOIN FETCH"] --> F["one query with orders"]
    F --> G["total: 1 prepare, 0 lazy fetches"]

What the top results cover, and what they skip

I read the top results for "detect n+1 queries spring boot test" on 20 Nov 2026:

Result Good at Missing
JavaHacks: How to Detect N+1 Queries in Tests Automatically The right core idea: generate_statistics, clear(), getPrepareStatementCount(), seed several parents, a QueryBudget helper Mentions the SessionFactory-wide pitfall, but does not show a failing lazy N+1 and a passing @EntityGraph in one runnable project, or a parallel-listings count.
axelix.io: Taming Hibernate in Tests Custom event listeners for lazy loads Heavier than a statistics snapshot, no simple budget assertion I can paste.
fabioformosa/n-plus-one-query-problem-detector @ExpectMaxQueries, scan mode, a note that parallel tests pollute the counters A library. The gap I wanted is the no-library test that fails first.
query-analyzer @NoNPlusOne Same: a dependency, not a raw Statistics test.
jplusone Reports lazy-loading trees Again a library, not a Hibernate-statistics budget.

So the gap is a small Spring Boot project that fails on a lazy N+1, passes after @EntityGraph / JOIN FETCH, and shows why clear() and single-threaded tests matter, with the counts pasted from a run. That's this post.

Setup

What Value
JDK Temurin OpenJDK 25.0.5 (--release 21)
Framework Spring Boot 4.1.2, Hibernate ORM 7.4.13.Final, H2 in PostgreSQL mode
Data 10 Customer rows, 3 ShopOrder rows each, lazy @OneToMany
Tests JUnit, @SpringBootTest, @Execution(SAME_THREAD)
Run it ./run.sh in the project folder (6 tests, a few seconds)
spring.jpa.properties.hibernate.generate_statistics=true
spring.jpa.open-in-view=false

open-in-view is off so a lazy load outside a transaction would fail loudly, not hide in a view interceptor. The service methods are @Transactional(readOnly = true), which is how a real listing should touch collections.

1. A budget helper, not a fingerprint of the whole test class

public static Snapshot measure(EntityManagerFactory emf, Supplier<T> action) {
    Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
    stats.setStatisticsEnabled(true);
    stats.clear();
    T result = action.get();
    return new Snapshot(
            stats.getPrepareStatementCount(),
            stats.getQueryExecutionCount(),
            stats.getCollectionFetchCount(),
            result);
}

clear() is the whole trick. Call it immediately before the code under test, not at the start of the class, so seed inserts are not in the budget. I assert a number that describes the listing, then I also check the service still returned 10 summaries with 3 orders each, so a "fast" query that dropped the collection cannot sneak through.

The naive service is just findAll() plus orders.size():

@Transactional(readOnly = true)
public List<CustomerSummary> listNaive() {
    return customers.findAll().stream()
            .map(c -> new CustomerSummary(c.getId(), c.getName(), c.getOrders().size()))
            .toList();
}

That produced prepareStatements=11 queryExecutions=1 collectionFetches=10. One query execution loads the 10 customers; the ten collection fetches are the N. getPrepareStatementCount() is the number I budget against, because it counts what was sent to the database.

2. @EntityGraph and JOIN FETCH both brought it to 1

@EntityGraph(attributePaths = "orders")
@Query("select c from Customer c")
List<Customer> findAllWithOrdersGraph();

@Query("select distinct c from Customer c join fetch c.orders")
List<Customer> findAllWithOrdersJoinFetch();

distinct on the join-fetch query is there so a customer with 3 orders is not returned three times. Both listings in the run were prepareStatements=1 queryExecutions=1 collectionFetches=0. Same summaries: 10 customers, 3 orders each.

I would use @EntityGraph when the same repository method sometimes needs the collection and sometimes does not (a second method without the graph stays lazy). JOIN FETCH is explicit in the JPQL. They measured the same here. Pagination plus JOIN FETCH is a different trap (the fetch join and a LIMIT do not mix well); this listing is the whole table of 10, and I am not claiming a page size.

3. The counters belong to the SessionFactory, not to your test

Three results from the same run, all about forgetting that:

[pitfall] forgot stats.clear(): counter was already 43, listing added 1, total 44
[pitfall] first naive listing 11 prepares; without clear, a second listing made the counter 22
[pitfall] two naive listings in parallel after one clear -> prepareStatements=22 (not isolated per test)

43 is not a magic number. It is whatever the seed (delete + 10 customers + 30 orders) and the tests that had already run had accumulated on the shared SessionFactory. The listing itself still added 1. If you assert == 1 without clear(), you will fail with a large number and chase the wrong bug.

The 11-then-22 case is the same counter without a second clear(). The parallel case is why the test class is annotated @Execution(SAME_THREAD) and why I would not turn on JUnit's parallel mode for a suite that reads Statistics. Two naive listings after one clear() ended at 22, which is correct as a sum and useless as a per-test budget.

The run

Pasted from RESULTS.txt, 20 Nov 2026, 08:28 IST. OpenJDK 25.0.5, Spring Boot 4.1.2, Hibernate 7.4.13.Final.

[n+1] JOIN FETCH list of 10 customers -> prepareStatements=1 queryExecutions=1 collectionFetches=0
[pitfall] two naive listings in parallel after one clear -> prepareStatements=22 (not isolated per test)
[n+1] naive list of 10 customers (touch orders) -> prepareStatements=11 queryExecutions=1 collectionFetches=10
[n+1] @EntityGraph list of 10 customers -> prepareStatements=1 queryExecutions=1 collectionFetches=0
[pitfall] forgot stats.clear(): counter was already 43, listing added 1, total 44
[pitfall] first naive listing 11 prepares; without clear, a second listing made the counter 22
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

The [n+1] and [pitfall] lines are interleaved because the methods did not run in source order. The counts are what matter.

Checklist

  • Enable hibernate.generate_statistics in the test profile only.
  • Seed at least several parents, each with children, so a per-row query cannot hide as "two statements".
  • stats.clear() immediately before the service call, then assert a budget (<= 2 or == 1), not a count of the whole test method including inserts.
  • Also assert the business result (10 summaries, each with 3 orders here) so a query that skips the collection cannot pass.
  • Prefer getPrepareStatementCount() plus getCollectionFetchCount() over reading logs by eye.
  • Keep these tests on one thread. The SessionFactory counter is shared.
  • After you fix an N+1, lower the budget to the new number so the problem cannot return unnoticed.

Interview follow-ups

"What's the N+1?" One query for N parents, then one query per parent for a lazy association. Here, 1 + 10. The "1" is findAll(). The "N" showed up as collectionFetches=10.

"@EntityGraph vs JOIN FETCH vs FetchType.EAGER?" The first two load the collection for this query only. EAGER loads it on every find, including the ones that do not need it, and can still N+1 if you have two eager collections. I would not "fix" N+1 by flipping the mapping to EAGER.

"batch size default_batch_fetch_size=16?" That groups the 10 collection fetches into fewer round trips (often 1 IN (...) fetch). It can drop 10 fetches toward 1, and it is still a fetch of the collection after the parent query, not a single join. I did not measure batch fetching in this run, so I am not quoting a count for it.

"Why not datasource-proxy or p6spy?" They work, and they can count SQL even when Hibernate statistics are off. This post stays on the API Hibernate already ships, which is enough for a JPA test.

"Can I assert this in a @DataJpaTest?" Yes. I used @SpringBootTest so the service and its @Transactional boundary are the same as production. The QueryBudget helper only needs an EntityManagerFactory.

Sources

Written by Gowtham M. Code tested on OpenJDK 25.0.5 / Spring Boot 4.1.2 / Hibernate 7.4.13.Final, 20 Nov 2026.


Preparing for a Java backend interview? My eBook Crack the Java Backend Interview has tested answers with runnable code for questions like this one. Get it for ₹99.

Nice one, the part about the counter belonging to the SessionFactory is what I'd have got wrong.