Video in progress
When and how do you use `@EntityGraph` in Spring Data JPA?
To tell a repository method which lazy associations should be loaded together in that query. It gives the effect of join fetch without writing JPQL, and it also works with derived query methods.
📖 Answer
Say Order has customer and items as LAZY. The list page needs only the customer, the detail page needs both:
public interface OrderRepository extends JpaRepository<Order, Long> {
@EntityGraph(attributePaths = "customer")
List<Order> findByStatus(Status status);
@EntityGraph(attributePaths = {"customer", "items", "items.product"})
Optional<Order> findDetailedById(Long id);
}
The method name stays as it is, and Spring adds the needed JOINs to the query.
You can also declare a named graph on the entity:
@NamedEntityGraph(name = "Order.detail",
attributeNodes = {@NamedAttributeNode("customer"), @NamedAttributeNode("items")})
@Entity
public class Order { ... }
@EntityGraph("Order.detail")
Optional<Order> findDetailById(Long id);
Things to watch in practice:
- If you add several
Listcollections to one graph, you getMultipleBagFetchException. - A graph with collections plus
Pageablehas the in-memory pagination problem, just likejoin fetch. - In Spring Data the default type is
FETCH: attributes not in the graph are treated as LAZY.
In my experience @EntityGraph is convenient for simple cases; for a query with complex filters, writing the JPQL with join fetch is still clearer.
Sign up to mark studied questions and save your progress.