Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate (JPA) how to do an eager query, loading all child objects

Tags:

Relating to my earlier question, I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this:

select distinct o from Order o left join fetch o.orderLines

Assuming a model with an Order class which has a set of OrderLines in it.

My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an Order for each OrderLine. Am I doing the right thing?

Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using FetchType.EAGER as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache?

like image 564
Chris Kimpton Avatar asked Sep 16 '08 10:09

Chris Kimpton


2 Answers

Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed.

I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderline if orderline has an order as its parent.

like image 123
James Law Avatar answered Oct 14 '22 13:10

James Law


I'm not sure about using the fetch keyword in your EJBQL, you might be getting it confused with the annotation...

Have you tried adding the FetchType property to your relationship attribute?

@OneToMany(fetch=FetchType.EAGER)?

See:

http://java.sun.com/javaee/5/docs/api/javax/persistence/FetchType.html http://www.jroller.com/eyallupu/entry/hibernate_exception_simultaneously_fetch_multiple

like image 35
Jeremy Avatar answered Oct 14 '22 13:10

Jeremy