Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL / Nested Eager Loading

Tags:

java

hql

eager

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!

like image 496
user973479 Avatar asked Oct 21 '25 11:10

user973479


1 Answers

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 ...
like image 172
JB Nizet Avatar answered Oct 23 '25 01:10

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!