Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to configure lazy/eager loading for each JPA query

457723Nov 26 2011 — edited Dec 5 2011
Hi!

I have extensive EJB model (entities with many child entities, entities with association to other large (many fields, BLOBs including) entities, and so on) and I would like for each JPA query configure what properties or associated entities (actually - in arbitrary depth) of selected entities should be fetched.

E.g. for one query I would like to fetch only Order (and no data of associated entities), but for other queries I would like to fetch Order, Order.Customer, Order.ShippingAddress.ZipCode and nothing else ( e.g. if there is Ordere.Route, Order.Billing and other associations, then I would like not to waste resources for fetching them). In both case the select clause of query can include only Order, but the results should be different - i.e. - there is no associated data in the first case and there are some associated data the second case.

I know that one solution is to declare all associations as lazy and then - after reading the result of query - do some touching for retrieving the associated data:
String check = order.Customer.toString();
check = order.ShippingAddess.ZipCode.toString();

But I see 2 problems with this: 1) it is not nice (resources are wasted for simply touching associated entities); 2) I assume that each "touch" operation generates other query to database that could be executed together with the original query. So - it would be nice to configure JPA query somehow to let it know which associations will be required from the result and which not.

What is the best practice?

I found, that JBoss server has lazy-loading-group configuration, but - I guess - it is JBoss specific:
http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/4.2/html/Server_Configuration_Guide/Loading_Process-Lazy_loading_Process.html
besides - it is XML and it would be more pretty if query configuration could be done with annotations!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 2 2012
Added on Nov 26 2011
2 comments
1,331 views