Sub topic 5
Finding N+1 with SQL Logs and Hibernate Statistics
This chapter assumes you know the Author and Book model from the earlier chapters. It also assumes you understand lazy loading and the persistence context. Here you will make the N+1 problem visible, so you can measure it before you fix it.
Why you must measure first
N+1 does not throw an error. The code returns correct results, and the only symptom is more SQL than you expected. With five authors in a test database it looks fast. With five thousand authors in production it does not. So the first step is to count the statements your code actually sends.
Turn on the settings
Add these three lines to application.properties:
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.SQL=DEBUGEach line has a job:
logging.level.org.hibernate.SQL=DEBUGprints every SQL statement Hibernate sends.generate_statistics=truemakes Hibernate collect counters, such as how many statements it prepared.open-in-view=falsestops lazy loading from working outside a transaction. A hidden lazy load then fails with an exception instead of quietly adding queries. A later chapter covers this setting in detail.
Run the suspect code
Here is the service method from the previous 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.findAll().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}
}findAll() loads the authors with one query. Each call to getBooks().size() then initializes a lazy collection, which runs one more query per author. With three authors, the log looks like this:
select a1_0.id,a1_0.name from author a1_0
select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?
select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?
select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?The signature is the same select ... from book ... where author_id=? statement repeated. One query for the list plus N queries for the children gives 1 + N.
Read the log
Look for these patterns when you scan a log:
- One statement repeated many times with only the parameter changing.
- A query on a child table immediately after a query on its parent table.
- A statement count that grows with the number of rows returned.
The SQL log shows the shape of the problem. It does not give you one number to compare, and it gets noisy with concurrent requests. Statistics fill that gap.
Count statements with Hibernate statistics
With generate_statistics=true, Hibernate logs a summary at the end of each session. It looks like this:
Session Metrics {
1200 nanoseconds spent acquiring 1 JDBC connections;
4 JDBC statements; ...
}You can also read the counters in code. The Statistics object returns the prepared statement count:
Statistics statistics = entityManagerFactory
.unwrap(SessionFactory.class)
.getStatistics();
statistics.clear();
authorService.authorSummaries();
long count = statistics.getPrepareStatementCount();Call clear() first so earlier work does not inflate the number. For the three-author example, count is 4. Add one author and it becomes 5. A fixed query would stay at 1 no matter how many authors exist.
Common errors
- Testing with tiny data. Two rows hide the problem. Load a realistic number of rows when you measure.
- Reading only the first query. The slow part is often the repeated statements further down the log.
- Leaving DEBUG logging on in production. It is expensive and can expose data. Use it in development and tests.
- Forgetting
clear(). Counters accumulate, so a count from an earlier call can mislead you.
Exercise
A log shows one select ... from author followed by 40 identical select ... from book where author_id=? statements. How many authors were loaded, and which Hibernate setting would let a test assert the total statement count?
Show answer
40 authors were loaded, since each author triggered one lazy collection query. Setting spring.jpa.properties.hibernate.generate_statistics=true enables the statistics, and a test can then read getPrepareStatementCount(), which here would be 41.