Sub topic 7
Fixing N+1 with @EntityGraph
This chapter assumes you know the Author and Book model from earlier in the tutorial, Spring Data JPA repositories, and how JOIN FETCH works. An entity graph achieves the same result as JOIN FETCH, but you declare it on the repository method and leave the query alone.
What an entity graph does
An entity graph is a list of attributes that Hibernate should load together with the root entity. You attach it to a repository method with @EntityGraph. Hibernate then adds a join to the generated SQL and fills the lazy attributes in the same statement.
Without a graph, authorSummaries() runs one query for the authors and one query per author for the books. With a graph on findAll(), it runs one query.
import java.util.List;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Override
@EntityGraph(attributePaths = "books")
List<Author> findAll();
@EntityGraph(attributePaths = "books")
List<Author> findByNameStartingWith(String prefix);
@EntityGraph(attributePaths = "books")
@Query("select a from Author a")
List<Author> findAllWithBooksUsingGraph();
}The three methods show the three common uses. You can override an inherited method, annotate a derived query, or annotate a @Query method. The JPQL in the third method contains no fetch clause.
Checking the result
Use the settings from the detection chapter and call authorSummaries() again. The log should show a single select containing left join book, and the statistics should report one prepared statement.
Paths and graph types
attributePaths accepts several attributes, and dotted paths reach into nested associations. For example, "books.publisher" would load each book's publisher too, if your model had one.
The graph type controls what happens to attributes that you did not list:
| Type | Listed attributes | Unlisted attributes |
|---|---|---|
| `FETCH` (default) | Loaded eagerly | Treated as lazy, even if mapped `EAGER` |
| `LOAD` | Loaded eagerly | Keep their mapped fetch type |
For N+1 work the default is usually what you want.
Differences from JOIN FETCH
- A graph uses a left outer join. An author with no books still appears in the result. A plain
join fetchin JPQL is an inner join and would drop that author. - The graph is attached to the method, so the same query text can be reused with and without it.
- Named graphs (
@NamedEntityGraphon the entity) are possible. InlineattributePathsis simpler and is enough in most projects.
Pitfalls that still apply
An entity graph does not change how Hibernate handles collections.
- Pagination: if you pass a
Pageableto a method whose graph includes a collection, Hibernate loads all rows and applies the limit in memory. It logs warning HHH000104 when this happens. Use the two-step id query shown in the pitfalls chapter. - Multiple bags: a graph that lists two
Listcollections can throwMultipleBagFetchException. Fetch only one collection per query. - Row multiplication: a graph over a collection returns one SQL row per book. Hibernate 6 removes the duplicate
Authorobjects for you.
Exercise
A method annotated with @EntityGraph(attributePaths = "books") returns an author who has no books. Would the same author appear if you wrote "select a from Author a join fetch a.books" instead, and why?
Show answer
No. An entity graph uses a left outer join, so the author is kept with an empty collection. A plain join fetch in JPQL is an inner join, so authors without books are dropped unless you write left join fetch.
Exercise
You add @EntityGraph(attributePaths = "books") to a method that takes a Pageable and returns Page<Author>. What problem should you expect?
Show answer
Hibernate cannot apply the limit in SQL when a collection is joined. It loads all rows and paginates in memory, logging HHH000104. Page the author ids first, then fetch those authors with their books.