Hibernate Query Cache Example

Hibernate Query Cache Example shows you how Query Cache works with Second level cache. Hibernate Query Cache is used with Second level cache but it does not cached the entities unlike Second Level Cache. Query Cache is caching the combination of query and values provided as parameters as key, and list of identifiers of objects returned by query execution as values. Notice that Hibernate will load objects using cached identifiers from second level cache.

Other interesting posts you may like

Let’s begin:

How to enable Query Cache in Hibernate

Add this property in hibernate configuration file

Then set query cacheable true with below syntax,

Create project directory structure
In this Hibernate Query Cache Example, we are creating a maven project in the Eclipse, final project directory structure will look like below image

Hibernate Query Cache Example

Hibernate Configuration file

Query cache is enabled in hibernate configuration file. However Query cache always used with Second level cache, we must enable Second level cache too. If you don’t know about Second level cache yet, please the tutorial Hibernate Second Level Cache Example

In this example, we are using EHCache for second level cache. This configuration makes sure that EHCache works normally.

Now create a program to test Hibernate query cache example

As you see above, we need to enable query cache in java program by setting cacheable true like this below main class.

Run above main and output is printed like below:

Let’s look at the output:

Step 1: Query cache is set false, by default. We load student object by query and query log is fired.
Step 2: Query cache is set true. Then we load student object by query again. As you see that query log is still fired here. It means that the student object is not stored yet in query cache before (step 1). Actually, the student object is just stored in this step 2.
Step 3: Query cache is set true. One more, we load student object by query and query log doesn’t appear. It means that student object is load from query cache.

That’s it on the Hibernate Query Cache Example.


Leave a Comment


Please share it if you found this useful
Hide Buttons