nimo23
nimo23

Reputation: 5698

jpql "join fetch" vs EntityGraph

I want to load related entities by using either jpql or jpa entity graph.

It seems both do the same thing.

Why should I use Entity Graphs instead of plain jpql? Are there any benefits?

What is the difference of using jpql:

select distinct u from User u join fetch u.hobbies a join fetch a.tasks

or Entity Graph:

@NamedEntityGraph(name = "User.eagerfetch", attributeNodes = { 
        @NamedAttributeNode("hobbies"),
        @NamedAttributeNode("tasks")})

Upvotes: 9

Views: 6731

Answers (1)

user3852017
user3852017

Reputation: 308

Difference is level of professional maturity of the code.

Clarity and readability, maintainability and code quality is significantly better with NamedEntityGraphs.

EntityGraph are evaluated compile time and it is less error prone as it is tightly coupled with the Entity definition. Any changed to Entity class breaks the Graph definition so that code does not even compile with those mistakes unlike with query strings. Hand written queries are hack solution. Not to mention that all the entity definitions are on one place; in the @Entity class not all over the place.

Upvotes: 5

Related Questions