Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Speed Up Your Hibernate Applications with Second-Level Caching : Page 4

Newer Hibernate developers sometimes don't understand Hibernate caching and use it poorly as a result. However, when used correctly, it can be one of the most powerful ways to accelerate Hibernate applications.


advertisement

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>



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.



John Ferguson Smart is principal consultant at Wakaleo Consulting, a company that provides consulting, training, and mentoring services in Enterprise Java and Agile Development. Well known in the Java community for his many published articles and talks, he is also the author of the book Java Power Tools.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap