Friday, June 1, 2012

Enabling EH Cache for Hibernate

For some reason, Hibernate ships with a pretty old version of EH Cache, and from my experience, using a version of EH Cache that is not shipped by Hibernate doesn't always work well with Hibernate.

On the other hand, the documentation provided by EH Cache always refer to the newest version, which doesn't always work with the one shipped by Hibernate.

In a nutshell, getting Hibernate to work with EH Cache involves the following steps:
  1. Setting up EH Cache:
    1. Use the ehcache.jar file provided by Hibernate.
    2. Need to download backport-util-concurrent.jar (Latest version is 3.1 at time of writing and seems to work fine).
    3. Configure ehcache.xml and put it on the classpath. It should have a "defaultCache" element as a template and then a separate "cache" element for each entity class (with fully qualified class name as the "name" of the cache).
    4. For the query cache, add a "cache" element with name "org.hibernate.cache.StandardQueryCache".
    5. Configure cache behavior as desired.
  2. On Hibernate's side:
    1. In hibernate.cfg.xml, add the following lines (subtle differences with documentation due to older version of EH Cache used and things Hibernate did when packaging EH Cache.):
      1. <property name="cache.use_second_level_cache">true</property>
      2. <property name="cache.use_query_cache">true</property>
      3. <property name="cache.provider_class">org.hibernate.cache.SingletonEhCacheProvider</property>
    2. And then in the mapping file for each entity (in the "class" element), add (above the "id" and "property" elements):
      1. <cache usage="read-write" />
References:

No comments:

Post a Comment