Video in progress
How do you automatically catch N+1 appearing in an integration test?
Count the SQL statements sent during the test through Hibernate Statistics or datasource-proxy, and assert against the expected value. Then if someone opens a lazy association inside a loop, the test fails right away.
📖 Answer
Finding N+1 by reading the log works, but it doesn't stop regressions. I write a "query budget" for an endpoint or a service method.
With Hibernate statistics:
@SpringBootTest(properties = "spring.jpa.properties.hibernate.generate_statistics=true")
class OrderQueryTest {
@Autowired EntityManagerFactory emf;
@Autowired OrderService service;
@Test
void listDoesNotTriggerNPlusOne() {
Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
stats.clear();
service.findRecentOrders(50);
assertThat(stats.getPrepareStatementCount()).isLessThanOrEqualTo(2);
}
}
getPrepareStatementCount() gives the number of statements that actually went to the database. getEntityFetchCount() and getCollectionFetchCount() show the number of lazy loads, and those are exactly what grow when there's an N+1.
Datasource-proxy (or libraries built on it) counts select/insert/update separately at the JDBC level and also sees code outside Hibernate.
Important conditions:
- there must be enough test data: N+1 isn't visible with a single order, so put in at least 3-5 records;
- if the test itself is
@Transactional, entities left in the context can hide the query; prepare the data in a separate transaction and callem.clear(); - don't leave
generate_statisticson permanently in prod, since it has overhead.
Sign up to mark studied questions and save your progress.