What is the difference between EntityGraph and Join Fetch?
sobes.tech AI
Answer from AI
EntityGraph and Join Fetch are two methods of managing the loading of related entities in JPA, but they differ in application and flexibility.
Join Fetch is a directive in JPQL or Criteria API that indicates the need to perform an SQL JOIN and load related entities immediately. Example:
TypedQuery<Person> query = em.createQuery(
"SELECT p FROM Person p JOIN FETCH p.address WHERE p.id = :id", Person.class);
query.setParameter("id", 1L);
Person person = query.getSingleResult();
Advantages:
- Easy to use in a specific query.
- Explicitly specify which associations to load.
Disadvantages:
- Tightly coupled to a specific query.
- Can lead to complex and bulky queries when many associations are involved.
EntityGraph is a declarative way to describe the loading graph of entities, which can be applied both to queries and repository methods. It allows flexible management of association loading without changing JPQL.
Example of creating and using an EntityGraph:
EntityGraph<Person> graph = em.createEntityGraph(Person.class);
graph.addAttributeNodes("address");
Map<String, Object> props = new HashMap<>();
props.put("javax.persistence.fetchgraph", graph);
Person person = em.find(Person.class, 1L, props);
Advantages:
- Reusable loading graphs.
- Separation of loading logic from the query.
- Can be combined with different queries.
Disadvantages:
- Requires additional configuration.
- May have limitations in complex cases.
Summary: Join Fetch is an explicit way to specify loading of associations in a query, while EntityGraph is a more flexible and declarative mechanism for managing the loading graph, which can be used independently of the query.