Reputation: 387
Using the JPA EntityManager and the JPA Query object, how can I override something that has the annotation @OneToMany(fetch = FetchType.EAGER) to be fetched lazily in a query?
If I had the hibernate Query object, I could have it create a criteria object and using this, set the fetch type to be lazy. But I have to use the JPA Query object. Is there any solution for this problem?
Upvotes: 13
Views: 9325
Reputation: 10395
The accepted answer is no longer true since Hibernate 5.4.22 (see HHH-8776). It is now possible to control fetch type dynamically even for EAGER
attributes by supplying javax.persistence.fetchgraph
query hint.
Assuming you have a Query
(or TypedQuery
), you can effectively set all associations to be lazy by supplying an empty entity graph:
EntityGraph<Child> entityGraph = entityManager.createEntityGraph(Child.class);
query.setHint("javax.persistence.fetchgraph", entityGraph);
List<Child> children = query.getResultList();
Or you can specify exactly what attributes you want to fetch eagerly by invoking
entityGraph.addAttributeNodes("parent");
Upvotes: 0
Reputation: 4703
Look into Hibernate Fetch profiles, or JPA Entity Graphs. This problem has been solved since you've asked the question in 2012.
Upvotes: 0
Reputation: 691775
There is no way to do that, even with the native Hibernate API. If an association is defined as EAGER, it will always be eagerly loaded, and there's no way to change that using a query.
The reverse is not true: you can eagerly-load a lazy association using a query.
Upvotes: 8