Sub topic 13
Guarding against regressions with query-count tests
This chapter assumes you can read the Author and Book model from earlier chapters and know how to find N+1 statements in SQL logs and Hibernate statistics. You should also be comfortable with Spring Boot tests (@SpringBootTest, JUnit 5, AssertJ).
Fixing an N+1 problem once is not enough. A later change can bring it back without any visible error. Someone adds a field to a response, calls getBooks() in a new place, or changes a fetch type. The code still compiles, the functional tests still pass, and the endpoint gets slower in production. A query-count test turns "this operation uses one statement" into a build failure.
What a query-count test checks
A query-count test runs one operation against a real database and asks Hibernate how many SQL statements it prepared. It compares that number with a limit you chose on purpose. Ordinary tests check results. This test checks cost.
The test does the following:
- Seeds a known amount of data.
- Clears Hibernate's statistics.
- Runs the operation under test.
- Reads the counter and asserts on it.
Which counters to read
Hibernate's Statistics object exposes several counters. They measure different things.
| Counter | What it counts | Use it when |
|---|---|---|
| `getPrepareStatementCount()` | JDBC statements Hibernate prepared | You want the total SQL cost. This is the best default. |
| `getQueryExecutionCount()` | HQL/JPQL queries you ran | You want to ignore lazy loads and see only explicit queries. |
| `getCollectionFetchCount()` | Lazy collections that were initialized | You want to see lazy collection loading specifically. |
| `getEntityFetchCount()` | Entities loaded by id or lazy proxy | You want to see proxy initialization specifically. |
getQueryExecutionCount() stays at 1 for the N+1 example in this tutorial, because the extra statements come from collection loads, not from queries you wrote. A test built on that counter would pass while the problem was still there. Use the prepared statement count unless you have a reason to be narrower.
A complete test
First apply the fix to the service so that the test has something to protect. This uses the findAllWithBooks() repository method from the JOIN FETCH chapter.
@Service
public class AuthorService {
private final AuthorRepository authorRepository;
public AuthorService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAllWithBooks().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}
}The test below seeds data with JdbcTemplate, so the entities need no extra constructors or setters. It assumes Spring Boot's default naming (tables author and book, column author_id) and an embedded database.
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootTest
class AuthorQueryCountTest {
@Autowired
EntityManagerFactory entityManagerFactory;
@Autowired
AuthorService authorService;
@Autowired
JdbcTemplate jdbc;
@AfterEach
void clean() {
jdbc.update("delete from book");
jdbc.update("delete from author");
}
private void seed(int authors, int booksPerAuthor) {
for (int i = 1; i <= authors; i++) {
jdbc.update("insert into author (name) values (?)", "Author " + i);
}
for (int b = 1; b <= booksPerAuthor; b++) {
jdbc.update("insert into book (title, author_id) select 'Book', id from author");
}
}
private long countStatements(Runnable action) {
Statistics statistics = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
statistics.setStatisticsEnabled(true);
statistics.clear();
action.run();
return statistics.getPrepareStatementCount();
}
@Test
void summariesUseOneStatement() {
seed(5, 3);
long count = countStatements(() -> authorService.authorSummaries());
assertThat(count).isEqualTo(1);
}
}Run the test against the old findAll() version of the service and it fails with a count of 6: one query for the authors plus one per author. That failure is the regression you want to catch.
Details that make the test trustworthy
Do not annotate the test with @Transactional
Spring's test support wraps a @Transactional test in one transaction. Everything inside shares one persistence context. If you seed entities through a repository in that transaction, they stay in the first-level cache. The later findAll() returns those same instances, and their books collections are already initialized. The test then reports zero lazy loads even when production would produce N+1. Seeding with JdbcTemplate, or committing the seed in a separate transaction, keeps the persistence context empty when the measured code runs.
Seed more than one parent row
With a single author, N+1 is two statements, and a weak assertion such as "fewer than three" would let it through. Use at least five parents. Use an isEqualTo assertion, or a small explicit upper bound, so that any added statement is noticed.
Test that the count does not grow
An exact number such as 1 is fragile if you later switch to batch fetching, which gives 1 + ceil(N / batchSize). The more durable property is that the count does not depend on the data size. Measure at two sizes and compare:
@Test
void statementCountDoesNotGrowWithData() {
seed(5, 2);
long small = countStatements(() -> authorService.authorSummaries());
clean();
seed(60, 2);
long large = countStatements(() -> authorService.authorSummaries());
assertThat(large).isEqualTo(small);
}Add this method to the same test class. Sizes 5 and 60 are on purpose. With default_batch_fetch_size=50, 5 authors need one batch and 60 authors need two. This test would then fail, which correctly tells you the cost still grows, only more slowly. If that growth is acceptable, assert the exact formula instead.
Keep the measured block small
The counter includes every statement prepared between clear() and the read. Put the seed and any cleanup outside that window. Inside it, call only the operation under test. If the operation allocates ids from a database sequence, those sequence calls count too. Write your expected number with that in mind, or measure read paths only.
Do not run these tests in parallel
Statistics belong to the SessionFactory, which is shared by every test in the same Spring context. Another test running at the same time adds statements to your count. Keep query-count tests in classes that do not run concurrently, or give them their own context.
Choosing what to protect
You do not need a count test for every repository method. Add them where a regression would be costly and likely:
- Endpoints that return lists with related data, since these are the usual N+1 sources.
- Methods that you fixed after a production incident.
- Mapping code, such as DTO assemblers, that touches associations on entities. It is the most common place for a lazy load to appear by accident.
A small number of well-chosen tests is more useful than blanket coverage. Each test needs seed data and a decision about the expected number, so keep that number in the test itself instead of in a shared constant that hides what the code costs.
Alternatives to Hibernate statistics
Hibernate statistics are enough for most projects, and they need no extra dependency. Some libraries count statements at the JDBC level instead, for example datasource-proxy or Hypersistence Utils with its SQL statement count validators. They count what actually reaches the driver, and they can separate selects from inserts and updates. That is useful when you want to assert "exactly one select and no updates". Both approaches serve the same purpose, so pick one and use it consistently across the project.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Count is always 0 | Statistics were not enabled, or data came from the first-level cache | Call `setStatisticsEnabled(true)` and avoid `@Transactional` on the test |
| Count is higher than expected by a constant | Seed or cleanup statements fall inside the measured window | Move them before `clear()` |
| Test passes locally and fails in CI | Parallel tests share the `SessionFactory` | Disable parallel execution for these classes |
| Test passes but production is slow | Test data has a single parent row, or only `getQueryExecutionCount()` is checked | Seed several parents and read `getPrepareStatementCount()` |
| `LazyInitializationException` in the test | Code touches a lazy association outside a transaction | Fix the code, which is what `open-in-view=false` is for |
Exercise
A teammate writes a query-count test for a service method. The test class is annotated with @Transactional, seeds two authors with books using authorRepository.save(...), then asserts that the method uses at most 2 statements. It passes even though the method still has an N+1 problem. Give two reasons the test is too weak and say how to fix each.
Show answer
First, the @Transactional test keeps the seeded entities in one persistence context, so findAll() returns the cached instances and their collections are already initialized, which hides the lazy loads. Fix: remove @Transactional from the test and seed with JdbcTemplate or in a separate committed transaction. Second, two authors make N+1 cost only 3 statements, and the bound of 2 is a loose limit rather than the exact expected count. Fix: seed at least five authors and assert an exact count (or that the count is the same at two data sizes).