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:
The Maven snippet is for Ehcache 2.0 and any upgrades is:
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.
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.
Before you configure caching for entities and collections, decide on the proper caching strategy to be used. You may select from:
Upcoming versions of Ehcache will also support the transactional strategy.
Configure entities to be cached using the cache strategy setting in hbm.xml:
Users of Java 5.0 Annotation based configuration will configure caching on the class definition itself using the @Cache annotation:
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:
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 element to your cache definition:
Then, before starting your hibernate application with Ehcache, make sure at least one Terracotta server is running:
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:
For more information on configuring Ehcache as a Hibernate second level cache, see: