A fetch strategy determines how Hibernate retrieves associated entities and collections from the database. It works with a fetch plan: the plan selects what enters the object graph, while the strategy selects how that data is loaded. section 12.0
Choose a strategy per procedure and use case rather than relying on one global setting:
- Lazy loading retrieves associations on demand and can produce the n+1 selects problem when navigation triggers many small queries. section 12.2
- Eager loading retrieves larger portions of the graph earlier, reducing query count but potentially creating oversized result sets and Cartesian products. section 12.2
- Mapping defaults provide a global baseline, while JPQL, CriteriaQuery, SQL queries, and entity graphs can tailor retrieval for a particular operation. section 12.2
Loading an item with its seller
An Item mapping can keep seller lazy, then request a load graph for one operation. A graph containing seller causes Hibernate to join ITEM and USERS, while unspecified attributes retain their mapping fetch settings. A fetch graph instead makes listed attributes eager and unspecified attributes lazy, effectively ignoring mapping FetchType settings. section 12.3.2
Path: Ch12/fetchloadgraph/src/test/java/com/manning/javapersistence/ch12 /fetchloadgraph/FetchLoadGraph.java Map<String, Object> properties = new HashMap<>(); properties.put( "javax.persistence.loadgraph", em.getEntityGraph(Item.class.getSimpleName()) #1 ); Item item = em.find(Item.class, ITEM_ID, properties); // select * from ITEM where ID = ? #1 The name of the entity graph we’re using is <kbd>Item</kbd>, and the hint for the <kbd>find()</kbd> operation indicates it should be the load graph. This means attributes that are specified by attribute nodes of the entity graph are treated as <kbd>FetchType.EAGER,</kbd> and attributes that aren’t specified are treated according to their specified or default <kbd>FetchType</kbd> in the mapping.
Inspect the runnable-looking EntityGraph configuration and the resulting SQL for applying a load graph to em.find(). section 12.3.2
