Search code examples
javahibernatejpaentityentitygraph

What's the goal of the JPA Entity Graph?


I’ve been learning about JPA and I found that we can use entity graph since JPA 2.1.

But I've not understood the merit of the entity graph yet.

I know that one of the merits to use an entity graph is we can specify only the data which we want to get among the whole entity, but in case we want to a whole entity, is there any other reason to use an entity graph?

Or we should use entity graphs only when we want to retrieve partial data?

If there is some other purpose or merit when we use entity graph, I would like to know it.


Solution

  • In JPA/Hibernate fetching entities with associations has always been a question for performance.

    • Lazily loading associations with in a transaction again and again results in n+1 select issues and to avoid such issues JPQL join fetch and Criteria api joins are used. But fetching data with these two also result in Cross join issues means Cross join of all table records are returned to application by hibernate.
    • Also altering fetch variable defined in annotations on entity level is also not a good option for use case to use case basis.
    • Hence to solve the above two issues entity graphs has been introduced. All nodes defined in entity graphs are always eager fetched irrespective of their definition on entity level. These graphs are passed as a hint to queries.
    • By passing graphs as a hint Cross join issues are solved as well annotation level specified fetch behavior of an association can also be changed.

    For code you can check my Github repository.