I have a piece of code similar to the following:
public void doQuery(final Baz baz){
final Query query = getSessionFactory().getCurrentSession().createQuery(
"select distinct foo from Foo as foo "+
"join foo.a as a"+
"join foo.b as b "+
"join b.c as c "+
"where baz=:baz"
);
query.setParameter("baz", baz);
final List<Foo> list = query.list();
for (final Foo foo : list) {
final Set<C> cSet = foo.getB().getCs();
final String value = foo.getSomeValue();
for (final C c : cSet) {
final Long key = c.getSomeLong();
// Do stuff with key and value
}
}
}
Every time the for loop is executed it will run additional hibernate queries behind the scenes to pull the extra data (since the Objects are marked as lazy loaded). Switching those Objects to eager is not desired because other classes that use the POJO do not need that data.
Obviously the code above can create a bottleneck which is something I'd like to avoid. Is there a hibernate-specific way (i.e. no native SQL) of modifying the query to bring back only the necessary data in one shot?
I'm fine with having the query return a String[][] with col1 as the key and col2 as the value instead of returning Foo
Update:
I changed the query to just return the key/values necessary
"select distinct c.id, foo.someValue from ...