简体   繁体   中英

Hibernate Query Optimization

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 (ie 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 ...

As I understand you question you don't want to have the collection eager by default but in these concrete case/method fetch all in one query?!

Here is the fragment from hibernate documentation concerning this:

A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. See Section 19.1, “Fetching strategies” for more information.

from Cat as cat
    inner join fetch cat.mate
    left join fetch cat.kittens

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM