Rodiq » Posts for tag 'hibernate'

hibernate level 2 jboss cache

After struggling throw a maze of documentation about jboss treecache, here are the things I would have liked to read somewhere, but found out by trial and error (and with the help of Adi and Len, thanks again!):

- to configure a cache for hibernate, the best documentation and source of jars is – they struggled to determine  a good combination that just works

-in the exact release of hibernate you are using there are the jars for all recommended caches (ehcache, treecache, oscache etc.) and a short file explaining what jars you need for each cache

-a comparison between all caches is found here in the hibernate documentation:

For me treecache was the only option, as i needed a “cluster safe” solution. Ehcache documentation mentions distributable feature, but apparently (as it results from hibernate documentation) ehcache in combination with hibernate it is not quite cluster safe.

As I tested with jboss, i downloaded exactly the hibernate version that came with my jboss, and took only jgroups.jar, there was already available the jboss-cache-jdk50.jar and did not copy jboss-cache.jar (i searched for the hibernate jar in jboss installation and looked at the manifest to find the exact version, then downloaded the full release of that version from

My mbean configuration in hibernate-services.xml (the equivalent of a hibernate.cfg.xml):

<attribute name="CacheProviderClass">org.hibernate.cache.TreeCacheProvider</attribute><attribute name="QueryCacheEnabled">true</attribute>
<attribute name="SecondLevelCacheEnabled">true</attribute>
<attribute name="StatGenerationEnabled">true</attribute>
<attribute name="UseStructuredCacheEntriesEnabled">true</attribute>

The treecache.xml contains the specific cache configuration, I copied it without any change from the etc directory of hibernate release (it is the “pessimistic” configuration) into my .sar root.

Good, after all this, it just works, but do not expect any miracles, in order to actually use the cache, you should make changes in your code and hibernate mappings, as explained in the hibernate documentation. These changes may be particular for the cache you installed, for instance “read-only” usage is not supported by treecache, “transactional” is recommended.

In the class mappings the cache attribute is required for the objects that will use the cache:

<class name="..." table="...">
  <cache usage="transactional"/>
    <bag name="children" table="..." inverse="true">
    <cache usage="transactional"/>
    <key column="PARENT_FK" />
    <one-to-many class="...."/>

The queries that shoud have the results cached need to be marked as such (and the query cache shoud be enabled in hibernate configuration):

Query query = session.createQuery("...");

Hope it helps, I still stick to my opinion that using a cache is a final option, it’s always better not to need it…