Hibernate Tips: Use the QueryCache to avoid additional queries

Hibernate Tips is a new series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.

Question:

Hibernate does not use the first- and second-level for queries. Is there any way to cache the result of a query?

Solution:

Hibernate also supports the QueryCache, which can store the result of a query. You need to activate it in the persistence.xml file by setting the parameter hibernate.cache.use_query_cache to true and defining a hibernate.cache.region.factory_class (see l. 12-13).

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="my-persistence-unit">
		...

		<properties>
			...

			<! –  configure caching – >
			<property name="hibernate.cache.use_query_cache" value="true"/>	
			<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
		</properties>
	</persistence-unit>
</persistence>

And you also need to activate caching for the specific query of which you want to cache the results by calling the setCacheable of the Hibernate-specific Query interface with the parameter true.

Session s = (Session) em.getDelegate();
		Query q = s.createQuery("SELECT a FROM Author a WHERE id = :id");
		q.setParameter("id", 1L);
		q.setCacheable(true);
log.info(q.uniqueResult());


Learn more:

I get into more details about Hibernate’s 3 different kinds of caches in the Hibernate Performance Tuning Online Training.
 

Hibernate Tips Book







Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.

Get it now!


Related Articles

Responses

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. Hi,

    What if my query is a constructor query? Can this be cached?

    1. Hi Jacob,

      Yes, the query result gets cached, but not the instantiated object. So, Hibernate will instantiate new objects every time you execute the query.

      Regards,
      Thorben