title: Hibernate Query Optimization
body: <p>I have a piece of code similar to the following:</p>
  
  <pre><code>  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&lt;Foo&gt; list = query.list();
  
      for (final Foo foo : list) {
          final Set&lt;C&gt; 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
          }
      }
    }
  </code></pre>
  
  <p>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.  </p>
  
  <p>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?</p>
  
  <p>I'm fine with having the query return a String[][] with col1 as the key and col2 as the value instead of returning Foo</p>
  
  <p>Update:</p>
  
  <p>I changed the query to just return the key/values necessary</p>
  
  <p>"select distinct c.id, foo.someValue from ...</p>