In current chapter I am going to explain how to use Hibernate Query Cache to avoid amount of traffic between your application and database. The query cache is responsible for caching the results of queries. Let us have a look how Hibernate uses the query cache to retrieve objects.
Note that the 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. So the query cache should always be used in conjunction with the second-level cache.
How the Query Cache Works:
Query query = session.createQuery("from Student as student where student.id = ? and student.studentName = ?"); query.setInt(0, Integer.valueOf(1)); query.setString(1, "Dinesh Rajput"); query.setCacheable(true); List l = query.list();
The query cache works something like this:
*----------------------------------------------------------------------------------------* | Query Cache | |----------------------------------------------------------------------------------------| | ["from Student as student where student.id = ? and student.studentName = ?", [ 1 , "Dinesh Rajput"] ] -> [ 2 ] ] | *----------------------------------------------------------------------------------------*
The combination of the query and the values provided as parameters to that query is used as a key, and the value is the list of identifiers for that query. Note that this becomes more complex from an internal perspective as you begin to consider that a query can have an effect of altering associations to objects returned that query; not to mention the fact that a query may not return whole objects, but may in fact only return scalar values (when you have supplied a select clause for instance). That being said, this is a sound and reliable way to think of the query cache conceptually.
Using the query cache
Two hibernate properties control whether the query cache is enabled:
- hibernate.cache.use_second_level_cache=true|false
- hibernate.cache.use_query_cache=true|false
The first turns on the second level cache in general and the second turns on the query cache regions. If the second is set to false, the query and timestamp cache regions are not created or used.
In the Next Chapter we will discuss more about the Hibernate Batch Processing.
<<Previous Chapter 32<< >>Next Chapter 34>>