Query cache effectively holds on to the identifiers for an individual query.
"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."
Once enabled via the configuration of Hibernate, it is simply a matter of calling setCacheable(true) on your Query or Criteria object.
****************************** How the Query Cache Works ******************************
The query cache is actually much like the association caching described above; it´s really little more than a list of identifiers for a particular type (although again, it is much more complex internally). Let´s say we performed a query like this:
Query query = session.createQuery("from Person as p where p.parent.id=? and p.firstName=?");
query.setInt(0, Integer.valueOf(1));
query.setString(1, "Ram");
query.setCacheable(true);
List l = query.list();
The query cache works something like this:
*----------------------------------------------------------------------------------------*
| Query Cache |
|----------------------------------------------------------------------------------------|
| ["from Person as p where p.parent.id=? and p.firstName=?", [ 1 , "Ram"] ] -> [ 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.
If the second-level cache is enabled (which it should be for objects returned via a query cache), then the object of type Person with an id of 2 will be pulled from the cache (if available in the cache), it will then be hydradated, as well as any associations.
5