em.createQuery("select p from Post p where p.id=:id", Post.class)
There are two hints available in JPA 2.1 for configuring the Entity Graph loading strategy.
javax.persistence.fetchgraphwill load all attributes defined in the EntityGraph, and all unlisted attributes will use LAZY to load.
javax.persistence.loadgraphwill load all attributes defined in the EntityGraph, and all unlisted attributes will apply it's fetch settings.
What problem it resolved
If you are using Hibernate, you have to encounter the famousLazyInitializedExcpetionwhen you try to fetch values from association attributes of an entity outside of an active Session.
There are some existed solutions to resolve this problem. In a web application, most of case, this exception could be thrown in the view layer, one solution is introduce Open Session in View pattern, in Spring application, an OpenInView AOP Interceptor(for none web application) and an OpenInView web Filter(for web application) are provided.
Now, the Entity Graph could be another robust solution for resolving this issue. For those cases which require to hint the lazy association of an Entity, create a Entity Graph to load them when the query is executed.
Some JPA providers, such asOpenJPA, provide aFetch Planfeature, which is similar with the Entity Graph.
The Entity Graph overrides the default loading strategy, and provides flexibility of loading the association attributes of an Entity.
The sample codes are hosted on my github.com account, check out and play it yourself.