title: How is getHibernateTemplate().setCacheQueries() supposed to be used properly?
body: <p>In some piece of our code we are using HibernateDaoSupport's setCacheQueries() method. At first we had a function <code>getByGroupId()</code> that just called <code>setCacheQueries(true)</code>, but when doing integration testing this caused Hibernate to throw "duplicate exceptions".
  So I googled around a bit and saw that many used a pattern where they enabled cache before doing a query and disabling it afterwards. I then tried disabling caching after the query, and the duplication bug disappeared. Now I am wondering what this pattern really does? The code below is modeled after this pattern.</p>
  
  <pre><code>import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
  public class MyDao extends HibernateDaoSupport{
  
    public List getByGroupId(Long groupId) {
      getHibernateTemplate().setCacheQueries(true);
      List result = getHibernateTemplate().find(
                      "from Selection where groupId = ? order by sortOrder ASC", groupId);
      getHibernateTemplate().setCacheQueries(false);
      return result;
    }
  }
  </code></pre>
  
  <p>I am unsure on how Spring and Hibernate works together here. If <code>setCacheQueries(false)</code> would empty all cached queries it would make no sense, but if it just disables caching of later queries (until <code>setCacheQueries(true)</code> is called) it would make a little more sense.</p>
  
  <ul>
  <li>Is this pattern of turning on/off caching before and after doing queries normal?</li>
  <li>Does it work (i.e. are the queries cached)?</li>
  <li>Any idea why it would cause Hibernate to throw exceptions about duplicate entries when not calling <code>setCacheQueries(false)</code> after the query?  </li>
  </ul>