How does Entity Graph differ from JOIN FETCH?
sobes.tech AI
Answer from AI
Entity Graph and JOIN FETCH are both used in JPA/Hibernate to optimize the loading of related entities, but they have different approaches and capabilities.
-
JOIN FETCH is a directive in JPQL or Criteria API that indicates performing an SQL JOIN and immediately loading related entities. It is a strict method applied to a specific query and affects the SQL structure.
-
Entity Graph is a declarative mechanism that allows describing which associations to load without changing the query. Entity Graph can be applied to different queries, making it more flexible and reusable.
Key differences:
- Entity Graph can be used for dynamic management of loading (fetch plan) without modifying JPQL.
- JOIN FETCH is embedded directly into the query and can lead to data duplication when multiple associations are involved.
- Entity Graph supports both eager (EAGER) and lazy (LAZY) loading, whereas JOIN FETCH is always eager.
Example of using Entity Graph:
@EntityGraph(attributePaths = {"orders", "profile"})
List<User> findAll();
JOIN FETCH example:
SELECT u FROM User u JOIN FETCH u.orders
In summary, Entity Graph is a more flexible and declarative way to manage loading, while JOIN FETCH is more explicit and query-specific.