Sub topic 2
Finding N+1 with SQL Logs and Hibernate Statistics
Assume you know basic Java, Spring Data JPA, SQL joins, and JPA mappings. This chapter uses Author and Book, where one author has many books.
Finding N+1 with SQL Logs and Hibernate Statistics
An N+1 problem occurs when one query loads the authors, then one additional query loads books for each author. For 10 authors, the application may execute 11 statements.
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.SQL=DEBUGThe SQL log reveals repeated statements. Hibernate statistics provide a measurable count:
Statistics statistics =
entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
statistics.setStatisticsEnabled(true);
statistics.clear();
authorService.authorSummaries();
long statements = statistics.getPrepareStatementCount();A query-count test can fail when a future change reintroduces N+1 behavior.
flowchart TD
A[Load authors] --> B[One author query]
B --> C[Access author.books]
C --> D[One book query per author]
D --> E[N plus 1 SQL statements]Fixing N+1 with `JOIN FETCH`
A fetch join loads the authors and books in one SQL query. distinct removes duplicate author objects caused by the relational join.
@Query("select distinct a from Author a left join fetch a.books")
List<Author> findAllWithBooks();Use left join fetch when authors without books must also appear. Use join fetch when an author must have at least one book.
Fixing N+1 with `@EntityGraph`
An entity graph declares which associations should be loaded for a repository method without embedding the join in JPQL.
@EntityGraph(attributePaths = "books")
@Query("select a from Author a")
List<Author> findAllWithBooksUsingGraph();This approach keeps the query simple and makes the fetch plan visible at the method declaration.
Reducing Queries with Batch Fetching
Batch fetching groups lazy loads into IN queries. Instead of one query per author, Hibernate can load books for several authors at once.
spring.jpa.properties.hibernate.default_batch_fetch_size=50Batch fetching reduces the number of statements, but it does not guarantee one statement. Use a fetch join or projection when a particular read always needs the related data.
Exercise
Which solution should you try when a summary page always needs every author's book count?
Show answer
Prefer a DTO projection with an aggregate query, because it reads only the required values and avoids loading entity collections.