Enabling Entity and Query cache in Hibernate

1. Introduction

Amongst the performance related tasks I have been through, this has been one of them. The concern is that if the same query is invoked every time for a particular entity and the table data is not liable to change for a particular time slot, we can possibly cache the query results with Hibernate. This means that, if we want the details of a Student with id 1234, the query executes and hits the database only for the first request. The subsequent requests are served with the results from the query cache. This brings a high impact in the response time which we could notice. When we do this, we are also concerned about when the cache refreshes itself. We can do that easily with a simple configuration, which we will be exploring.

If a query cache is applied, then no subsequent SQL statement is sent to the database. The query results are retrieved from the query cache, and then the cached entity identifiers are used to access the second level cache.

2. Implementation

To enable query cache, below are the set of steps that needs to be followed –

  1. Set the hibernate.cache.use_query_cache property to true and make sure the second level cache is enabled. Follow this link to understand the second level cache.
  2. With that done, org.hibernate.cache.internal.StandardQueryCache holds the cached query results.
  3. In the ehCache configuration file, add the below snippet –
  4. The query cache does not cache the state of the actual entities in the cache. It caches identifier values and results of value type. Therefore, always use the query cache in conjunction with the second-level cache for those entities which should be cached as part of a query result cache – https://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch06.html
  5. To cache the concerned entity as specified in point 4, we need to add the following snippet into the XML entity mapping file as –

    The above makes sure that the non-lazy components of the entity are cached as part of a query result cache.
  6. With all the above points covered, the final point is to explicitly enable the query caching to the individual queries as –

With all this done, maybe you can start your server in debug mode and see the magic happen!

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.