Sub topic 13
Guarding against regressions with query-count tests
A fixed N+1 problem can come back without anyone noticing. A developer changes a fetch type, removes a join fetch, or adds a getter call in a loop, and every test still passes. This chapter adds a test that fails when the number of SQL statements goes up. It assumes you have read the earlier chapters on Hibernate statistics and on fixing N+1 with JOIN FETCH.
Why functional tests miss N+1
authorSummaries() returns the same strings whether it runs one query or 101. A normal assertion on the result cannot tell the difference. The only visible effect is more database round trips. So the test has to measure statements, not results.
The idea
Hibernate keeps counters in a Statistics object. The test follows these steps:
- Load known data with several parents.
- Clear the counters.
- Call the code under test.
- Assert on the statement count.
The fixed service
The test only means something if the code under test is the fixed version. Here authorSummaries() uses the join fetch query from the earlier chapter.
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAllWithBooks().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}The test
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.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
@SpringBootTest
@Sql("/authors-with-books.sql")
class AuthorQueryCountTest {
@Autowired
EntityManagerFactory entityManagerFactory;
@Autowired
AuthorService authorService;
@Test
void summariesUseOneStatement() {
Statistics statistics = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
statistics.setStatisticsEnabled(true);
statistics.clear();
authorService.authorSummaries();
assertThat(statistics.getPrepareStatementCount()).isEqualTo(1);
}
}authors-with-books.sql is a script in src/test/resources that inserts at least three authors, each with two or more books. @Sql runs it before the test method. statistics.clear() then discards the counts from that setup, so only the service call is measured.
Common mistakes
- Too little data. With one author, N+1 produces 2 statements and the bug looks small. Use at least three parents so the count grows with N.
- Wrapping the test in
@Transactional. The seeded entities then stay in the persistence context, and the service may find them already loaded. Lazy loads and queries can be skipped, so the test passes while production code still issues extra queries. Leave the test non-transactional and let the service open its own transaction. - Counting the wrong thing.
getQueryExecutionCount()counts only JPQL and HQL queries. Lazy collection loads are not counted there.getPrepareStatementCount()counts every JDBC statement, which is what you want here. - Forgetting
clear(). Without it, the setup inserts are counted too.
Choosing the assertion
An exact value such as isEqualTo(1) is the strictest check. It fails on both increases and decreases, which can be annoying when a harmless change merges two queries. Some teams use isLessThanOrEqualTo(2) for service methods that are expected to need a small, fixed number of statements. Either way, the number must not depend on how many rows the seed script contains.
Exercise
A query-count test for a method that returns authors with their books passes with isEqualTo(2) when the seed data has one author, but production logs show 101 statements. What is wrong with the test, and how do you fix it?
Show answer
With one author, the N+1 pattern issues 1 + 1 = 2 statements, so the test cannot tell the broken code from a fixed one. Seed at least three authors with books, and assert the count for the fixed code (for example 1). Then the broken code fails, because its count grows with the number of authors.