Wednesday, December 12, 2012

Using Hibernate Query Cache in Spring

The steps for configuring the EHCache query cache is the same as when not using Spring. The main difference is how queries is being indicated as cacheable. In Spring, queries are made via the a subclass DAO of the HibernateDaoSupport class, which provides a method to indicate whether all queries in the DAO should use the query cache.

This should be called in the initDao method.

   @Override
   protected void initDao() throws Exception {
       super.initDao();

       // this enables the usage of query cache for all queries in this DAO
       this.getHibernateTemplate().setCacheQueries(true);

       // the cache region name that should be used for this entity
       this.getHibernateTemplate().setQueryCacheRegion(“XXXXXXX”);

       // optional, for enabling statistics collection for profiling
       this.getHibernateTemplate().getSessionFactory().getStatistics().setStatisticsEnabled(true);
   }


Note that this is for the query cache, not the second-level cache, the latter which is used for "get" operations.

No comments:

Post a Comment