Sub topic 5
Finding N+1 with SQL Logs and Hibernate Statistics
This chapter assumes you can read basic JPA mappings, use Spring Data repositories, and know what a transaction is in Spring. You should also have seen the Author and Book model from earlier chapters, and you should know why lazy loading inside a persistence context can issue extra queries. Here you learn to see those queries. You can't fix a problem you can't measure.
Why detection comes first
N+1 rarely shows up as an error. The code compiles, the tests pass, and the page returns the right data. With 5 rows in a development database, the extra queries cost a few milliseconds. With 5,000 rows in production, they cost seconds and a lot of database round trips.
Two questions drive detection:
- How many SQL statements did this operation run?
- Which of those statements are the same query repeated with a different parameter?
SQL logging answers the second question well. Hibernate statistics answer the first one precisely. You will use both.
The code under investigation
The service method below is the one from the previous chapter. It loads all authors, then touches each author's lazy books collection.
@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() issues one query for the authors. Each call to getBooks().size() initializes one lazy collection, and each initialization is a separate query. For N authors that gives 1 + N statements.
Turning on the instruments
Add these three settings 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 distinct job:
| Setting | Effect |
|---|---|
| `logging.level.org.hibernate.SQL=DEBUG` | Logs every SQL statement Hibernate sends, as text with `?` placeholders. |
| `hibernate.generate_statistics=true` | Makes Hibernate count statements, entity loads, collection fetches, and cache hits. |
| `spring.jpa.open-in-view=false` | Disables Open Session in View, so lazy loading outside a transaction fails instead of silently running more queries. |
A later chapter covers Open Session in View in detail. For detection, the point is that leaving it on lets lazy loading in controllers and views run queries you never see in the service layer.
Do not use spring.jpa.show-sql=true as a substitute. It writes to standard output and bypasses your logging framework, so you can't filter it, route it, or turn it off per environment.
Reading the SQL log
With three authors in the database, calling authorSummaries() produces output 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 exact aliases differ between Hibernate versions, but the shape is always the same. One query selects the parents. Then the same child query repeats, once per parent. That repetition is the signature of N+1.
When you read a log, look for these signs:
- Identical statements, apart from the bound value, that appear many times in a row.
- A statement count that grows with the number of rows returned by the first query.
- A
where ... = ?orwhere ... in (...)on a foreign key column, such asauthor_id.
Limits of log reading
Logs are good for small, focused checks. They have weaknesses at scale:
- Under concurrent load, statements from different requests interleave, so you can't see which ones belong together.
- A hundred identical lines are easy to miss when thousands of other lines surround them.
- Logs show what ran, not how many times per request. Counting by eye is error-prone.
For these cases use statistics, which give you numbers.
Reading Hibernate statistics
When generate_statistics is on, Hibernate keeps counters in a Statistics object. It also logs a summary at the end of each session through the org.hibernate.engine.internal.StatisticalLoggingSessionEventListener logger. At INFO level, that summary looks like this:
Session Metrics {
104500 nanoseconds spent acquiring 1 JDBC connections;
0 nanoseconds spent releasing 0 JDBC connections;
613400 nanoseconds spent preparing 4 JDBC statements;
1812300 nanoseconds spent executing 4 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;
0 nanoseconds spent performing 0 L2C puts;
...
}The line to watch is preparing N JDBC statements. Here N is 4, which is 1 + 3 for three authors. If you add ten more authors, it becomes 14. A count that scales with data is the clearest proof of N+1.
Statistics also separate two related counters:
| Counter | Meaning |
|---|---|
| Prepared statement count | SQL statements sent to the database through JDBC. |
| Collection fetch count | Lazy collections loaded from the database. |
| Entity load count | Entity instances loaded. |
| Query execution count | HQL or JPQL queries run, not including lazy loads. |
Compare them. If the query execution count is 1 but the prepared statement count is 4, then three statements came from lazy loading that you didn't write as queries. That gap points to hidden loads.
Reading the counters in code
You can read the same counters directly. Unwrap the SessionFactory from the EntityManagerFactory and call getStatistics().
import jakarta.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
public final class StatisticsReport {
private StatisticsReport() {}
public static String describe(EntityManagerFactory emf) {
Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
return "statements=" + stats.getPrepareStatementCount()
+ ", queries=" + stats.getQueryExecutionCount()
+ ", collectionFetches=" + stats.getCollectionFetchCount()
+ ", entityLoads=" + stats.getEntityLoadCount();
}
}The counters are cumulative across the whole application. To measure one operation, call stats.clear() before it and read the counters after. That approach is not safe if other threads run queries at the same time, since their statements land in the same counters. In a single-threaded test, or a local experiment, it works well.
A repeatable measurement workflow
Use the same steps each time you suspect N+1 in an endpoint.
- Seed enough data that N is clearly greater than 1. Ten or more parents makes the pattern obvious.
- Enable the SQL log and statistics.
- Call the endpoint or service method once.
- Count the statements. Note whether the count tracks N.
- Double the number of parents and repeat. If the count doubles too, you have N+1.
- Apply a fix and run the same measurement again.
Step 5 is the most reliable check. A fixed cost, such as three statements regardless of N, is acceptable. A cost that grows with N is the problem.
Edge cases and common mistakes
Counting statements in the wrong place
Statistics count statements that Hibernate sends. They do not include SQL that other tools run on the same connection pool, such as a JdbcTemplate call or a Flyway migration. If your count looks too low, check for other data access paths.
Lazy loading that never happens
If the code never touches getBooks(), no extra queries run, so no N+1 exists in that path. A log with a single query is not a bug in the instrument. N+1 only appears when the lazy association is actually read. Test the same code path that production uses, including serialization. A JSON serializer such as Jackson reads every getter, so returning an entity from a controller can trigger lazy loads that a unit test of the service never reaches.
Small test data hides the problem
With one author, the log shows two statements and looks fine. Always test with several parents. A test with N = 1 can't distinguish 1 + N from a plain join.
Eager mappings produce N+1 too
Setting fetch = FetchType.EAGER does not remove the problem. For findAll(), Hibernate loads the parents first and then issues follow-up selects to satisfy the eager association. The log shows the same repeated pattern, but the queries run immediately rather than on first access. When you see repeated statements without any call to a lazy getter, check for eager mappings.
Statistics overhead
Collecting statistics has a small cost. It is fine in development, in tests, and for short diagnostic windows. Many teams leave it off in production by default and enable it temporarily. Measure before deciding for your own system.
Summary of the detection toolkit
| Tool | Best for | Weakness |
|---|---|---|
| SQL log (`org.hibernate.SQL`) | Seeing the shape and repetition of queries | Hard to count under load |
| Session metrics log | Quick per-session totals | Needs statistics enabled |
| `Statistics` API | Exact counts in code and tests | Counters are global unless cleared |
The next chapters apply fixes and then use these same counters to prove they worked. Later you will turn the measurement into an automated test, so the build fails if N+1 returns.
Exercise
A service method returns 20 authors and your statistics report 21 prepared statements. You then load 40 authors and see 41 statements. What does this pattern tell you, and which two tools from this chapter would you use to confirm which statements repeat?
Show answer
The count grows by one per parent (1 + N), which is the N+1 signature. Use the SQL log (logging.level.org.hibernate.SQL=DEBUG) to see the repeated child query, such as the select on book filtered by author_id. Use Hibernate statistics (getPrepareStatementCount() or the session metrics log) to get the exact count and to compare it with the query execution count. A prepared statement count far above the query execution count points to hidden lazy loads.
Exercise
Why does spring.jpa.show-sql=true fall short of logging.level.org.hibernate.SQL=DEBUG for diagnosing N+1 in a real application?
Show answer
show-sql writes straight to standard output, so it bypasses the logging framework. You can't filter it by logger, send it to a file with the rest of your logs, or switch it on and off per environment. The org.hibernate.SQL logger goes through your logging configuration and gives you that control.