hibernate: activating the second-level cache

Hibernate has two different cache levels: the first-level and the second-level cache. The first one is always activated. The second-level cache is up to you.

So, first-level cache, it’s related to session objects, i.e, objects on the managed state. These objects are results from a query, an object after inserted or updated. Again, first-level is activated by default.

In the other hand, second-level cache, when activated, it’s a in memory copy from the database. Hibernate still using the first-level cache, but, instead of querying directly the database it uses this second-level cache. Faster and do not overload the database.

The second-level it’s just a interface on Hibernate. You’ll need to use an implementation of second-level in order to get it working. In java, the most commonly used is the EHCache.

Technical speaking, to activated the EHCache you’ll need to add two properties in the Hibernate configuration:

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

Note: Depending on the Hibernate version, you’ll need different configuration. Please, checkout the EHCache help page.

Next step will configure Hibernate to make the cache of an object. Directly in the Hibernate configuration, add the cache tag or use theĀ annotation:

<cache usage="read-write|nonstrict-read-write|read-only" />
--
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

The last step is the EHCache configuration: ehcache.xml. We need to create and define an region for our cache. The default would be the class signature:

<ehcache>
  <cache
    name="com.rodrigow.Blog"
    maxElementsInMemory="200"
    eternal="true"
    overflowToDisk="true"
  />
</ehcache

Now is just a matter to turn on the Hibernate and EHCache logs and make sure you see some cache hit. There won’t have any SQL on database.

2 thoughts on “hibernate: activating the second-level cache

  1. Pingback: Tweets that mention hibernate: activating the second-level cache | rodrigow -- Topsy.com

  2. Tony

    I am using second level cache i.e Ehcache.But i need to update second level cache or refresh.Because it’s not showing the update record present in table.Always showing me the cache value.So that is an issue for me.

Leave a Reply

Your email address will not be published. Required fields are marked *