Configure Ehcache as a Second Level Cache

Overview

 

Terracotta Ehcache is a popular open source Java cache that can be used as a Hibernate second level cache.  It can be used as a standalone second level cache, or can be configured for clustering to provide a replicated coherent second level cache.

 

Installation

 

Hibernate ships with the ehcache library. Hibernate 3.5 will ship with Ehcache 1.5. Ehcache 2.0 came out too close to the final ship date for Hibernate 3.5, but we will update it to 2.0 in the next release of Hibernate. In the meantime, to use the new Ehcache provider you need to download it or, if you are using Maven, add it as a dependency. To download Ehcache, visit the Terracotta Ehcache download site:

 

Download Terracotta Ehcache

 

The Maven snippet is for Ehcache 2.0 and any upgrades is:

 

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>[2.0.0,]</version>
            <type>pom</type>
        </dependency>

 

 

Configuration

 

The Hibernate documentation Chapter 19.2 provides detailed information on configuring the Hibernate second level cache.  A brief overview of the steps is provided here for reference.

 

Step 1 - Configure Hibernate

 

First, configure Hibernate for second level caching and specify the second level cache provider:  Hibernate 3.3 introduced a new second level caching SPI, so if you are using Hibernate 3.3 or greater, be sure to take advantage of the new interface by selecting the appropriate configuration depicted below.

 

Hibernate 3.3 and above

 

<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>

 

Hibernate 3.2

 

<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>

 

Step 2 - Configure your entities, collections, and queries for caching

 

Next, update your hibernate configuration to configure entities, collections for caching.  To enable queries to be cached, you will need to update the code where the query is created to set caching enabled.

 

Cache Strategy

 

Before you configure caching for entities and collections, decide on the proper caching strategy to be used.  You may select from:

 

  • read-only
  • read-write
  • nonstrict-read-write

 

Upcoming versions of Ehcache will also support the transactional strategy.

Entities

 

Configure entities to be cached using the cache strategy setting in hbm.xml:

 

 

<class name="com.mypackage.MyEntity" table="...">
    <cache usage="read-write"/>
</class>

 

 

Users of Java 5.0 Annotation based configuration will configure caching on the class definition itself using the @Cache annotation:

 

 

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class MyEntity {
    ...
}

 

Collections

 

Configure collections to be cached using the cache strategy setting in hbm.xml:

 

<class name="com.mypackage.MyEntity" table="...">
    <cache usage="read-write"/>
     <set name="mySet">
         <cache usage="read-write"/>
    </set>
</class>

 

 

Users of Java 5.0 Annotation based configuration will configure caching on the class definition itself using the @Cache annotation:

 

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public class MyEntity {    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)    Set mySet = ...;    ...}
Query caching

 

You can also enable query caching.  To do so configure it in your hbm.xml:

 

<property key="hibernate.cache.use_query_cache">true</property>

 

 

Then, where queries are defined in your code, add the method call setCacheable(true) to the queries that should be cached:

 

return sessionFactory.getCurrentSession().createQuery("...").setCacheable(true).list();  

 

Step 3 - (Optional) Configure ehcache.xml

 

By default, Ehcache will create separate cache regions for each entity that you configure for caching.  You can change the defaults for these regions by adding the configuration to your ehcache.xml, an example is provided here:

 

<cache
    name="com.somecompany.someproject.domain.Country"
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="300"
    timeToLiveSeconds="600"
    overflowToDisk="true"
/>

 

 

More details on Ehcache settings for Hibernate can be found in the Ehcache documentation.

Step 4 - (Optional) Configure for clustered caching

Ehcache can be configured for clustered caching using the Terracotta platform.  Detailed instructions for installing and setting up Terracotta Ehcache as a clustered Hibernate second level cache are provided at terracotta.org.

 

If you downloaded Ehcache using the link above, you already have Terracotta installed.  Getting started with a clustered cache is very easy.   First, tell Ehcache to cluster your cache using Terracotta by adding the <terracotta/> element to your cache definition:

 

<cache
    name="com.somecompany.someproject.domain.Country"
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="300"
    timeToLiveSeconds="600"
    overflowToDisk="true">
    <terracotta/>
</cache>

 

Then, before starting your hibernate application with Ehcache, make sure at least one Terracotta server is running:

 

$ start-tc-server.sh

 

 

You can monitor the status of your clustered cache and view all of the Hibernate Metrics using the Terracotta Developer Console included with the Terracotta installation:

 

$ dev-console.sh

 

More Information

 

For more information on configuring Ehcache as a Hibernate second level cache, see: