Speed Up Your Hibernate Applications with Second-Level Caching (cont'd)

Using Query Caches

In certain cases, it is useful to cache the exact results of a query, not just certain objects. For example, the getCountries() method probably should return exactly the same country list each time it is called. So, in addition to caching the Country class, you could also cache the query results themselves.

To do this, you need to set the hibernate.cache.use_query_cache property in the hibernate.cfg.xml file to true, as follows:


    <property name="hibernate.cache.use_query_cache">true</property>
advertisement

Then, you use the setCacheable() method as follows on any query you wish to cache:


public class CountryDAO {

    public List getCountries() {
        return SessionManager.currentSession()
                             .createQuery("from Country as c order by c.name")
				     .setCacheable(true)
                             .list();
    }
}

To guarantee the non-staleness of cache results, Hibernate expires the query cache results whenever cached data is modified in the application. However, it cannot anticipate any changes made by other applications directly in the database. So you should not use any second-level caching (or configure a short expiration timeout for class- and collection-cache regions) if your data has to be up-to-date all the time.

Proper Hibernate Caching

Caching is a powerful technique, and Hibernate provides a powerful, flexible, and unobtrusive way of implementing it. Even the default configuration can provide substantial performance improvements in many simple cases. However, like any powerful tool, Hibernate needs some thought and fine-tuning to obtain optimal results, and caching—like any other optimization technique—should be implemented using an incremental, test-driven approach. When done correctly, a small amount of well executed caching can boost your applications to their maximum capacities.

Previous Page: Working with Cached Associations  


John Ferguson Smart has worked on many large-scale J2EE projects involving international and offshore teams for government and business entities. His specialties are J2EE architecture and development and IT project management. He also has a broad experience with open source Java technologies. Check out his technical blog at www.jroller.com/page/wakaleo.
Page 1: IntroductionPage 3: Working with Cached Associations
Page 2: Cache ConfigurationPage 4: Using Query Caches