Video in progress

Strong Middle 🐻 Hibernate and JPA

What's the difference between giving an entity graph as a "fetch graph" and as a "load graph"?

With a fetch graph, the attributes listed in the graph are treated as EAGER and all the others as LAZY. With a load graph, the ones in the graph become EAGER, while the others keep the FetchType from their mapping.

📖 Answer

In JPA the graph is given to the query as a hint:

EntityGraph<?> g = em.getEntityGraph("Order.withItems");

em.createQuery("select o from Order o where o.id = :id", Order.class)
  .setParameter("id", id)
  .setHint("jakarta.persistence.fetchgraph", g)   // or "jakarta.persistence.loadgraph"
  .getSingleResult();

The difference shows up on attributes that are marked EAGER in the mapping. Say Order.customer is a @ManyToOne (default EAGER) and the graph contains only items:

items customer (EAGER in the mapping)
fetch graph loaded LAZY per the specification
load graph loaded EAGER, loaded

A subtle point in practice: even in a fetch graph, Hibernate can't always "turn off" an EAGER @ManyToOne. If it can't create a proxy (in some @OneToOne cases, for example), it loads it anyway. So check the result in the SQL log, and don't trust the documentation blindly.

In Spring Data:

@EntityGraph(attributePaths = "items", type = EntityGraph.EntityGraphType.LOAD)
Optional<Order> findWithItemsById(Long id);

The default type is FETCH.

My habit: if all associations are LAZY in the mapping, the difference between the two types almost disappears, and the graph states exactly "what this query needs". The difference matters only in old projects where some EAGERs remain, and there a fetch graph helps cut extra JOINs.

You can also build a graph dynamically in code. This has been a standard API since JPA 2.1 (em.createEntityGraph(Order.class) and addAttributeNodes), and it's handy for reusing one repository method for different screens.