0 day streak
java / expert
Snippet

Dynamic Fetching Strategies using JPA EntityGraph

EntityGraphs provide a way to override fetch plans at runtime, solving the N+1 select problem without hardcoding 'EAGER' fetch types in entities. Using subgraphs, you can precisely define which nested associations should be fetched in a single JOIN query based on the specific use case.

snippet.java
java
1
2
3
4
5
6
7
8
9
public List<Order> findOrdersWithDetails(Long customerId) {
EntityGraph<Order> graph = em.createEntityGraph(Order.class);
graph.addSubgraph("items").addAttributeNodes("product");
return em.createQuery("SELECT o FROM Order o WHERE o.customer.id = :id", Order.class)
.setParameter("id", customerId)
.setHint("jakarta.persistence.loadgraph", graph)
.getResultList();
}
spring
Breakdown
1
EntityGraph<Order> graph = em.createEntityGraph(Order.class);
Creates a mutable root graph for the Order entity.
2
graph.addSubgraph("items").addAttributeNodes("product");
Defines a deep fetch path for nested associations within the order items.
3
.setHint("jakarta.persistence.loadgraph", graph)
Instructs the JPA provider to treat specified attributes as EAGER and others as LAZY.