Sobes.tech
Junior — Middle

How can hierarchical relationships between entities be implemented in JPA using Entity Graph?

sobes.tech AI

Answer from AI

The JPA Entity Graph is used to define which related entities should be loaded together with the main entity, helping to optimize queries and avoid the N+1 problem.

To implement hierarchical relationships with Entity Graph, you can:

  • Create a NamedEntityGraph specifying attributes, including nested relationships via subgraphs.
  • In the subgraph, specify second-level and further relationships, forming a hierarchy.

Example:

@Entity
@NamedEntityGraph(
    name = "Order.detail",
    attributeNodes = @NamedAttributeNode(value = "items", subgraph = "itemsSubgraph"),
    subgraphs = @NamedSubgraph(
        name = "itemsSubgraph",
        attributeNodes = @NamedAttributeNode("product")
    )
)
public class Order {
    @OneToMany(mappedBy = "order")
    private List<Item> items;
}

@Entity
public class Item {
    @ManyToOne
    private Product product;
}

When executing a query, you can specify this graph:

EntityGraph<?> graph = em.getEntityGraph("Order.detail");
Map<String, Object> props = new HashMap<>();
props.put("javax.persistence.fetchgraph", graph);
Order order = em.find(Order.class, orderId, props);

Thus, Order, its items, and related products are loaded hierarchically.