JPA, how can i have two queries, one use lazy and one use eager for fetching?

748 Views Asked by At

I have some nested objects, Package->Documents->Pages. The package contains a set of documents, the document contains a set of pages. I have the relationship with Pages->Documents and Documents->Pages both set to EAGER because when I request a package I want it to get all of the documents along with all of the pages.

Now I have another requirement to get only the Package->Documents, but I don't want to also retrieve Document->Pages because this query needs to be more efficient and doesn't need that data.

Is there a way using the same model objects that I can turn off the EAGER fetch? Or is there a way I can change it to LAZY and then force it to be eager without having to loop through every document in the package and call getPages()?

What's the preferred, most efficient way of doing this?

2

There are 2 best solutions below

0
On

It's all explained here: Difference between JOIN and JOIN FETCH in Hibernate

Set your relationship to lazy and write a query using join fetch to eagerly retrieve all children while keeping your regular query with a simple join to get data lazily.

0
On

As noted elsewhere you need to mark the relationship as LAZY and the deal with EAGER fetching when required rather than the other way around: once a relationship is marked as EAGER it is always eagerly fetched regardless of what you might specify in the query.

Once you have marked it as as LAZY however you obviously need a mechanism to enable EAGER fetching when required.

JPA 2.1 introduced a new feature - Entity Graphs - as a means to try and address (in an elegant way) the long standing problem of fetching to different depths in the Entity graph for different use cases.

You can read a bit more about Entity Graphs here:

https://blogs.oracle.com/theaquarium/entry/jpa_2_1_entity_graphs

http://www.radcortez.com/jpa-entity-graphs/

An alternative for Web applications is the Open Session in View Pattern which transparently enables 'on-demand' fetching and which might be worth a look.

http://blog.jhades.org/open-session-in-view-pattern-pros-and-cons/