liveBook · Manning

EntityGraph API

As explained in Java Persistence with Spring Data and Hibernate epub

@EntityGraph is a JPA annotation that declares an entity graph on an entity or query-related repository element.

The EntityGraph API defines a reusable fetch plan for JPA retrieval operations. An entity graph names entity attributes and associations to load, overriding or augmenting the entity’s default fetch plan when EntityManager.find() or a query executes. section 12.3 section 12.3.2

Use an entity graph by following this pattern:

  • Apply the same graph to JPQL or other query operations with setHint(), allowing one fetch plan to be reused across query forms. section 12.3

Loading an item and its seller

@NamedEntityGraph( name = "ItemSeller", attributeNodes = @NamedAttributeNode("seller") ) @Entity class Item { /* ... */ } Map<String, Object> properties = new HashMap<>(); properties.put("javax.persistence.loadgraph", em.getEntityGraph("ItemSeller")); Item item = em.find(Item.class, id, properties); This load graph treats seller as eager for the operation while leaving unspecified attributes governed by their mappings. A query can reuse the same graph with setHint().

A graph specifies what should be loaded, not how it must be loaded. A load graph eagerly treats listed attributes while retaining mapping defaults for others; a fetch graph uses the javax.persistence.fetchgraph hint and restricts fetching to graph attributes. Empty graphs therefore preserve the entity’s defaults. section 12.3 section 12.3.2

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains named, dynamic, nested, load, and fetch graphs, but stops short of unifying graph selection with SQL fetch strategy.
Examples
Demonstrates Item-seller loading, dynamic graphs, query hints, and nested Bid-item-seller-bids subgraphs.
What it assumes
Assumes basic Jakarta Persistence retrieval by identifier and teaches graph declarations, hints, and default fetch-plan interaction.
What you can do after
Apply it via EntityManager find and query hints to reuse fetch plans for direct and nested associations.
How it connects
Connects entity graphs with fetch plans, lazy loading, eager loading, fetch strategies, EntityManager, JPQL, and Criteria queries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.