Thursday, October 6, 2016

Second Level Cache in Hibernate

Caching is a mechanism for storing the loaded objects into cache memory. The advantage of this is, whenever we want to load the same object from the database, instead of hitting the database once again, it loads from the local cache memory, so that the no. of round trips between an application and the database gets reduced.

Caching mechanism increases the performance of the application.

In hibernate we have two levels of caching
First Level Cache [Session Cache]
Second Level Cache [Session Factory Cache or JVM Level Cache]


Whenever we are load any object from the database, hibernate verifies whether that object is available in the local cache memory of that particular session [first level cache], if not, then hibernate verifies whether the object is available in global cache or factory cache [second level cache], if not, then hibernate hits the database and loads the object.

It first stores in the local cache of the session [first level] and then in the global cache [second level cache]

When another session needs to load the same object from the database, then hibernate copies that object from global cache [second level cache] into the local cache of this new session.

Second level cache is from 4 vendors
EHCache Cache from hibernate framework
OSCache from Open Symphony
SwarmCache
TreeCache from JBoss


Steps to enable second level cache in hibernate ->

1) Add provider class in hibernate configuration file.

<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider </property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>


2) Add the following in hibernate mapping file.

<cache usage="read-only" />

3) Create ehcache.xml and store in at class path location [place where you have mapping and configuration xml’s] in web application.



No comments:

Post a Comment

Home