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.