Query result sets can also be cached. Query Cache is only useful for queries that are run frequently with the same parameters. For using the Query Cache we need to enable the query cache by the giving method:
hibernate.cache.use_query_cache true
This setting creates two new cache regions:
1. one holding cached query result sets (org.hibernate.cache.StandardQueryCache),
2. holding timestamps of the most recent updates to queryable tables (org.hibernate.cache.UpdateTimestampsCache).
We need to remember query cache does not cache the state of the actual entities in the result set; it caches only identifier values and results of value type. The query cache should always be used in conjunction with the second-level cache.
Most queries do not benefit from caching, so by default, queries are not cached. To enable caching, call Query.setCacheable(true). By the using the method it allows the query to look for existing cache results or add its results to the cache when it is executed.
When we want to fine-grained control over query cache expiration policies, the we need to specify a named cache region for a particular query by calling Query.setCacheRegion().
List blogs = sess.createQuery("from Blog blog where blog.blogger = :blogger")
.setEntity("blogger", blogger)
.setMaxResults(15)
.setCacheable(true)
.setCacheRegion("frontpages")
.list();
If the query should force a refresh of its query cache region, then we can call Query.setCacheMode(CacheMode.REFRESH). We can got benifit where underlying data may have been updated via a separate process (not modified through Hibernate) and allows the application to selectively refresh particular query result sets. This is a more efficient alternative to eviction of a query cache region via SessionFactory.evictQueries().