Sub topic 7
Fixing N+1 with @EntityGraph
This chapter assumes you know basic JPA mapping, Spring Data JPA repositories, and JPQL. You should also have read the previous chapter on JOIN FETCH. Here you will learn how @EntityGraph fixes the same N+1 problem without changing the query text, and where it behaves differently from JOIN FETCH.
What an entity graph is
An entity graph is a description of which associations to load together with a root entity. The query decides which rows to select. The graph decides which lazy associations to initialize in the same statement.
Spring Data JPA exposes this with the @EntityGraph annotation on repository methods. Hibernate turns the graph into a join in the generated SQL. The result looks like a JOIN FETCH, but the graph lives outside the query.
Recall the model from earlier chapters. Author has a lazy @OneToMany collection books. The service method authorSummaries() calls findAll() and then getBooks().size() for each author. That produces 1 query for the authors and N queries for the collections.
Basic usage
The repository below fixes the problem in one annotation.
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Query("select distinct a from Author a join fetch a.books")
List<Author> findAllWithBooks();
@EntityGraph(attributePaths = "books")
@Query("select a from Author a")
List<Author> findAllWithBooksUsingGraph();
}Both methods load authors and their books in a single joined query. The second method keeps the JPQL plain. The attributePaths value lists the associations to fetch eagerly for this call only.
You can also put @EntityGraph on derived query methods and on the inherited methods you redeclare. This is often the shortest fix:
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Override
@EntityGraph(attributePaths = "books")
List<Author> findAll();
}Redeclaring findAll() changes behavior for every caller, so use it only if every caller needs the books. Otherwise add a separately named method.
Why use a graph instead of JOIN FETCH
Both approaches produce similar SQL. The differences are practical.
| Aspect | `JOIN FETCH` | `@EntityGraph` |
|---|---|---|
| Where it is declared | Inside the JPQL string | As an annotation on the method |
| Works with derived queries such as `findByName` | No, you must write JPQL | Yes |
| Works on inherited methods like `findAll()` | No | Yes, if redeclared |
| Join type | Inner unless you write `left join fetch` | Left outer join |
| Filtering on the fetched association | Possible with an alias, but risky | Not possible, no alias |
| Reuse the same query with different fetch plans | Needs separate queries | Same query, different graphs |
The join type matters. join fetch a.books in the earlier example is an inner join, so authors with no books disappear from the result. An entity graph uses a left outer join, so those authors stay in the result with an empty collection. That difference can change results when you migrate from one style to the other.
Seeing the effect in the SQL
With the logging settings from the detection chapter, the graph version prints one statement instead of N+1:
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.SQL=DEBUGThe logged statement has this shape:
select a.id, a.name, b.id, b.author_id, b.title
from author a
left join book b on a.id = b.author_idThe Statistics prepared statement count for authorSummaries() drops from N+1 to 1 once the service calls a graph-backed method.
Fetching several levels deep
attributePaths accepts dotted paths for nested associations. Suppose Book also had a lazy @ManyToOne to a Publisher:
@EntityGraph(attributePaths = {"books", "books.publisher"})
List<Author> findByNameStartingWith(String prefix);This loads authors, their books, and each book's publisher in one statement. Be careful. Every level multiplies rows in the result set, which can make the query slow and the transfer large. Fetch only what the calling code uses.
Fetch graph versus load graph
@EntityGraph has a type attribute with two values from the JPA specification.
EntityGraphType.FETCHis the default. Attributes in the graph are fetched eagerly. Attributes not in the graph are treated as lazy, even if the mapping saysEAGER.EntityGraphType.LOAD. Attributes in the graph are fetched eagerly. Attributes not in the graph keep whatever the mapping says.
@EntityGraph(attributePaths = "books", type = EntityGraph.EntityGraphType.LOAD)
List<Author> findByNameContaining(String text);Hibernate does not always honor the "treat as lazy" rule for FETCH graphs on associations that are mapped EAGER. Rely on lazy mappings in the first place. The recommended pattern from earlier chapters is to map every association as lazy and add fetching per use case. Under that pattern the two types behave identically.
Named entity graphs
You can also define a graph on the entity and refer to it by name.
@Entity
@NamedEntityGraph(
name = "Author.withBooks",
attributeNodes = @NamedAttributeNode("books"))
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private List<Book> books = new ArrayList<>();
}public interface AuthorRepository extends JpaRepository<Author, Long> {
@EntityGraph("Author.withBooks")
List<Author> findByNameStartingWith(String prefix);
}Named graphs are reusable across several repository methods. They also put fetching knowledge on the entity, which couples the mapping to specific use cases. For most applications the inline attributePaths form is easier to read, because the fetch plan sits next to the method that needs it.
Limits that still apply
An entity graph is a JOIN FETCH in a different form, so it inherits the same problems.
- Pagination with collections. If a graph fetches a collection and you pass a
Pageable, Hibernate cannot applyLIMITin SQL, because joined rows multiply the parents. It loads all rows and paginates in memory. Hibernate logs a warning (HHH90003004) when this happens. Use the two-step id query shown in the pagination chapter instead. - Multiple bags. Fetching two
Listcollections without an index column in one graph throwsMultipleBagFetchException. Fetch one collection per query, change one to aSet, or use batch fetching for the second. - Cartesian growth. Two collections fetched together multiply rows, even when Hibernate allows the query.
- Duplicate roots. In Hibernate 6, duplicate parent entities from joined rows are removed automatically. Older versions need
distinctin JPQL. With the graph form, check which Hibernate version you run.
How the graph reaches Hibernate
Spring Data builds a JPA EntityGraph object from the annotation. It passes it to the query as a hint. Hibernate then adds the joins when it translates the query to SQL.
Because the graph is a query hint, it applies only to that query's result. Entities already in the persistence context keep their state. If an Author instance was loaded earlier in the same transaction with an uninitialized books collection, a later graph query returns the same instance, and Hibernate initializes the collection from the new result. Do not assume a graph guarantees a fresh load of unrelated data.
Common mistakes
- Redeclaring
findAll()with a graph and then calling it from code that never touchesbooks. Every caller pays for the join. - Using a graph on a paged query that fetches a collection and ignoring the in-memory pagination warning.
- Assuming graph results match the inner-join results of the earlier
join fetchquery. - Adding every association to
attributePaths"just in case". This replaces N+1 with a wide, slow join. - Using a graph where a DTO projection is enough. If the caller needs only a name and a count, entities are the wrong tool, as the projections chapter shows.
Exercises
Exercise
A repository method findByNameStartingWith(String prefix) is a derived query. You want it to return authors with their books loaded in one SQL statement. Which approach works without writing JPQL, and what is the join type?
Show answer
Add @EntityGraph(attributePaths = "books") to the method. Hibernate adds a left outer join, so authors without books are still returned.
Exercise
You replace select distinct a from Author a join fetch a.books with @EntityGraph(attributePaths = "books") @Query("select a from Author a"). Your test that expects 40 authors now sees 45. What is the likely cause?
Show answer
The original query used an inner join, so it dropped the five authors who have no books. The entity graph uses a left outer join, so those authors are now included with empty collections.
Exercise
A paged repository method returns Page<Author> and uses @EntityGraph(attributePaths = "books"). The logs show a warning about applying a limit in memory. Why does this happen, and what is the fix?
Show answer
A collection join repeats each author once per book, so SQL LIMIT would cut rows, not authors. Hibernate therefore loads all rows and paginates in memory. The fix is to page author ids in one query, then fetch those authors with their books in a second query that uses where a.id in :ids.