3

I am wondering what the best way is to load nested values for lazy loaded objects. I'm providing an example to help explain this better.

public class A{
    private B b; //Lazy loaded
    private C c; //Lazy loaded
    private D d; //Lazy loaded
}
public class B{
    private E e; //Lazy loaded
    private F f; //Lazy loaded
}
public class C{
}
public class D{
}

As an example I want to do:

System.out.println(a.getB().getE());

If I ran the above statement I'd get a lazy load exception.

I can always do the following:

for (A a : somePossiblyLargeList) {
    org.hibernate.Hibernate.initialize(a.getB().getE());
}

but obviously performance would suck.

Is there a way I can write a custom HQL query which returns A objects that are pre-populated with those specific nested fields?

Thanks!

user973479
  • 1,629
  • 5
  • 26
  • 48

1 Answers1

6

Of course.

Use join fetch in your HQL query, as explained in the Hibernate reference documentation (that you should read):

select a from A a left join fetch a.b b left join fetch b.e e where ...
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I think my actual situation is a bit trickier than my example... This is a many-to-many mapping between A<->B with a link table called A_Lnk_B. So, Class A contains a Set. From that list, I'd have to iterate over the ids for every B. Then I would take those ids in B to find E. I have a hard time conceptualizing how this would be stored back into a java A object... – user973479 Sep 30 '11 at 17:12
  • select a from A a left join fetch a.aLinkBs alb left join fetch alb.b b left join fetch b.e e where ... – JB Nizet Sep 30 '11 at 20:41
  • I can't believe i used a `ResultTransformer` and wasted 3 hours when `select a ..` was the answer. Thanks! – Varun Achar May 03 '13 at 18:22