Over a million developers have joined DZone.

Hibernate Tip: Use the QueryCache to Avoid Additional Queries [Video]

DZone's Guide to

Hibernate Tip: Use the QueryCache to Avoid Additional Queries [Video]

Hibernate's structure can pose query result caching problems for the uninitiated. Let's see how QueryCache solves the problem.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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


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


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">


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

And you also need to activate caching for the specific query you want to cache the results of 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);

And for more Hibernate recipes, check out my book Hibernate Tips: More than 70 solutions to common Hibernate problems.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

jpa ,hibernate ,querying ,caching ,java ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}