HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
1. Feel Free to ask and submit anything on and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

hibernate-caching: what is query cache and what is the use of query cache?

Please explain query cache and its uses.

hibernate x 23
caching x 2
Posted On : 2014-07-08 00:45:36.0
profile Rishi Kumar - Rishi Kumar


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 and p.firstName=?");
query.setInt(0, Integer.valueOf(1));
query.setString(1, "Ram");
List l = query.list();
The query cache works something like this:

| Query Cache |
| ["from Person as p where 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.

Posted On : 2014-07-08 01:08:26
Satisfied : 1 Yes  0 No
profile Garima Gupta - Garima Gupta
Reply This Thread

Post Answer
Please Login First to Post Answer: Login login with facebook -