my dog learned polymorphism
The moose likes Object Relational Mapping and the fly likes Alternating between Eager and Lazy Fetching Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Alternating between Eager and Lazy Fetching" Watch "Alternating between Eager and Lazy Fetching" New topic

Alternating between Eager and Lazy Fetching

Abiodun Adisa
Ranch Hand

Joined: Jan 17, 2002
Posts: 495
I have this code module, It fetches all objectes of Trans

Please how do i specify the type of fetching i want. At certain times i would want it to retrieve all associated objects (Eager), At other times it should not retrieve all associated objects
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

To eager fetch an association, you put a JOIN FETCH in the From clause. It can be LEFT or INNER join fetches.

so HQL would look like

Select p FROM Parent p LEFT JOIN FETCH p.children

One caveat is that you can only eager fetch one OneToMany or ManyToMany association. This is because if you do more than one you get a cartesian product.

You can do one Left and one Inner join fetch of OneToMany or ManyToMany association, but be sure that for the Many side, there is a guarantee that there is always at least one returned or the Parent doesn't load in the query. Just like an inner join in SQL resultset would do.

You can also look into the Fetching strategy of "subselect" so that the Many side association is loaded in just one more query rather than N number of queries.

Good Luck


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Joe May

Joined: Sep 28, 2009
Posts: 22
criteria queries allow you to specify a fetch mode
I agree. Here's the link:
subject: Alternating between Eager and Lazy Fetching
It's not a secret anymore!