Second Level Cache
Previous Home Next

Hibernate Session is a transaction-level cache of persistent data.Hibernate has the ability to configure a cluster or JVM-level (SessionFactory-level) cache on a class-by-class and collection-by-collection basis. we can plug in a clustered cache. We need to aware that caches are not having change mode to the persistent store by another application. So it can be called to configured to regularly expire cached data.

We have an another option in Hibernate which cache implementation to use by specifying the name of a class that implements org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class. Hibernate is combination of bundled with a number of own and plug it in as outlined above. we have to remember EhCache as the default cache provider.

We have given all cache provider in the table:

Cache Provider Class Type Cluster Safe Query Cache Supported
Hashtable (not intended for production use) org.hibernate.cache.HashtableCacheProvider memory Yes
EHCache org.hibernate.cache.EhCacheProvider memory, disk Yes
OSCache org.hibernate.cache.OSCacheProvider memory, disk Yes
SwarmCache org.hibernate.cache.SwarmCacheProvider clustered (ip multicast) yes (clustered invalidation)
JBoss Cache 1.x org.hibernate.cache.TreeCacheProvider clustered (ip multicast transactional yes (replication) yes (clock sync req.)
JBoss Cache 2 org.hibernate.cache.jbc2.JBossCacheRegionFactory clustered (ip multicast) transactional yes (replication or invalidation) yes (clock sync req.)

Generally we know that every session has its own cache memory. Cache is used to grow the performance of application and database. Caching is a mechanism for storing the loaded objects into a cache memory. By the help of the cache memory we can avoid the number of hits as many as possible to give a better performance for critical applications.

Advantage of cache mechanism:

When we want to load the same object from the database then instead of hitting the database once again, it loads from the local cache memory only, so that the number of round trips between an applications and databaase server got decreased. It means caching mechanism increase the performance of the application.Caching is important to Hibernate as well which utilizes a multilevel caching schemes.

How to do Cache mappings

We have given the simple cache code to understand the cache mapping. In the element of a class or collection mapping has the following form:


Tag description is given below:

usage(required)It specifies the cache strategy. In transactional,read-write, nonstrict-read-write or read only
region(optiona)Defaults to the classes or collection role name. It specifies the name of the second level cache region.
include(optional)It defaults to all.It work non-lazy. It speficies that properties of teh entity mapped with lazy = atribute can not be cached when attribute-level lazy fetching is enabled.

We can specify and elements in hibernate.cfg.xml. The usage attribute specifies a cache concurrency strategy.

Hibernate Second Level Cache Example

We know that in the hibernate cache first level cache is automatically generated but on the other hand second level cache we need to generate for making the session and to store the data and reusability the database object.

One small example for making the second level cache. In this we need some thing which are given below:

  1. Pro.java (POJO class)
  2. Logic.java
  3. Pro.hbm.xml)
  4. ehcache.xml
  5. hibernate.cfg.xml


package HibernateCache;
public class Pro
    private int protId;
    private String proName;
    private double price;
    public void setProId(int proId)
        this.proId = proId;
    public int getProId()
        return proId;
    public void setProName(String proName)
        this.proName = proName;
    public String getProName()
        return proName;
    public void setPrice(double price)
        this.price = price;
    public double getPrice()
        return price;


package HibernateCache;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Logic { 
    public static void main(String[] args)
        Configuration cfg = new Configuration();
        SessionFactory factory = cfg.buildSessionFactory();
        Session session1 = factory.openSession();
        Object o=session1.load(Pro.class,new Integer(105));
        Pro s=(Pro)o;
        System.out.println("Loaded object product name is___"+s.getProName());
        System.out.println("Object Loaded successfully.....!!");
        catch (Exception e) {
        System.out.println("6 seconds compelted......!!!!!!!!");
        Session session2 = factory.openSession();
        Object o2=session2.load(Pro.class,new Integer(105));
        Pro s2=(Pro)o2;
        System.out.println("Loaded object product name is___"+s2.getProName());
        System.out.println("Object loaded from the database...!!");
        Session session3 = factory.openSession();
        Object o3=session3.load(Pro.class,new Integer(105));
        Pro s3=(Pro)o3;
        System.out.println("Loaded object product name is___"+s3.getProName());
        System.out.println("Object loaded from global cache successfully.....!!");

Summary of Logic.java

  1. From line numbers 16 \E2?? 22 we opened session1 and loaded object and closed session1, this time object will be loaded from the database as its the first time
  2. Then from 27 \E2?? 31 we have been waited for 6 seconds, but in our ehcache.xml we have given timeToIdleSeconds=\E2?\9D5\E2?\B3 , i mean after 5 seconds object will be removed from the global cache
  3. And again in ForOurLogic.java line numbers 35 \E2?? 41 we opened second session and loaded the object, this time hibernate will loads the object from the database, and closed the session
  4. Immediately from 43 \E2?? 49 we opened session3 and loaded the object, this time hibernate will loads the object form the global session not from the database


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<class name="HibernateCache.Pro" table="products">
<cache usage="read-only" />
<id name="proId" column="pid"  />
<property name="proName" column="pname" length="10"/>
<property name="price"/>


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_pro?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
<property name="cache.provider_class">
<property name="dialect">org.hibernate.dialect.MySql</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="Pro.hbm.xml"></mapping>


<?xml version="1.0"?> 
<defaultCache maxElementsInMemory="100" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="200" />
<cache name="HibernateCache.Pro" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" />

Summary of ehcache.xml

  1. In ehcache.xml, if eternal=\E2?\9Dtrue\E2?\9D then we should not write timeToIdealSeconds, timeToLiveSeconds, hibernate will take care about those values
  2. So if you want to give values manually better eternal=\E2?\9Dfalse\E2?\9D always, so that we can assign values into timeToIdealSeconds, timeToLiveSeconds manually, and play ;)
  3. timeToIdealSeconds=\E2?\9Dseconds\E2?\9D means, if the object in the global chche is ideal, means not using by any other class or object then it will be waited for some time we specified and deleted from the global cache if time is exceeds more than timeToIdealSeconds value
  4. timeToLiveSeconds=\E2?\9Dseconds\E2?\9D means, the other Session or class using this object or not, i mean may be it is using by other sessions or may not, what ever the situation might be, once it competed the time specified timeToLiveSeconds, then it will be removed from the global cache by hibernate
  5. Actually will reflects to all the pojo classes in our application, and we can also assign the ehcache values to specified pojo class by
Previous Home Next