One of the great uses for this is integration tests. If you want to make sure that when a certain method is called, whatever comes back has certain things loaded, this is a good way to do it.
There are a couple of ways that a relationship set to use FetchType.EAGER
can end up not loaded.
When using a @NamedEntityGraph
, if you specify the hint to the query as javax.persistence.fetchgraph
, then the JPA provider should only load the relationships named in the entity graph. This is the difference between that and javax.persistence.loadgraph
, which loads relationships not specified in the entity graph using whatever fetch type they already had.
The problem, and the reason that I said the provider "should" only load those relationships, is that the JPA spec allows the provider to always load more than the specification requires. Hibernate, specifically, ignores the recommended behavior for fetchgraph, and treats it the same as loadgraph.
For Hibernate criteria queries you can override and set the fetch mode of any relationship explicitly using setFetchMode()
. I don't know about other providers.
Maybe there are others?
Ah, and as I was looking around for some more details I see that this has already all been said in another StackOverflow question here:
Ignore a FetchType.EAGER in a relationship