Tuesday, January 14, 2014

Configure Ehcache as a Second Level Cache


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.


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:

  1.         <dependency>  
  2.             <groupId>net.sf.ehcache</groupId>  
  3.             <artifactId>ehcache</artifactId>  
  4.             <version>[2.0.0,]</version>  
  5.             <type>pom</type>  
  6.         </dependency>  


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

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

Hibernate 3.2

  1. <property key="hibernate.cache.use_second_level_cache">true</property>  
  2. <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.

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

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

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

  1. @Entity  
  2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  3. public class MyEntity {  
  4.     ...  
  5. }  


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

  1. <class name="com.mypackage.MyEntity" table="...">  
  2.     <cache usage="read-write"/>  
  3.      <set name="mySet">  
  4.          <cache usage="read-write"/>  
  5.     </set>  
  6. </class>  

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

  1. @Entity  
  2. @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:

  1. <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:

  1. 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:

  1. <cache  
  2.     name="com.somecompany.someproject.domain.Country"  
  3.     maxElementsInMemory="10000"  
  4.     eternal="false"  
  5.     timeToIdleSeconds="300"  
  6.     timeToLiveSeconds="600"  
  7.     overflowToDisk="true"  
  8. />  

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 element to your cache definition:

  1. <cache  
  2.     name="com.somecompany.someproject.domain.Country"  
  3.     maxElementsInMemory="10000"  
  4.     eternal="false"  
  5.     timeToIdleSeconds="300"  
  6.     timeToLiveSeconds="600"  
  7.     overflowToDisk="true">  
  8.     <terracotta/>  
  9. </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:


oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes