Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

Second Level Cache

Hibernate second level cache uses a common cache for all the session object of a session factory. It is useful if you have multiple session objects from a session factory.

SessionFactory holds the second level cache data. It is global for all the session objects and not enabled by default.

Different vendors have provided the implementation of Second Level Cache.

  1. EH Cache
  2. OS Cache
  3. Swarm Cache
  4. JBoss Cache

Each implementation provides different cache usage functionality. There are four ways to use second level cache.

  1. read-only: caching will work for read only operation.
  2. nonstrict-read-write: caching will work for read and write but one at a time.
  3. read-write: caching will work for read and write, can be used simultaneously.
  4. transactional: caching will work for transaction.

The cache-usage property can be applied to class or collection level in hbm.xml file. The example to define cache usage is given below:

  1. <cache usage=“read-only” />

Let’s see the second level cache implementation and cache usage.

Implementation read-only nonstrict-read-write read-write transactional
EH Cache Yes Yes Yes No
OS Cache Yes Yes Yes No
Swarm Cache Yes Yes No No
JBoss Cache No No No Yes

3 extra steps for second level cache example using EH cache

1) Add 2 configuration setting in hibernate.cfg.xml file

  1. <property name=“cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>
  2. <property name=“hibernate.cache.use_second_level_cache”>true</property>

2) Add cache usage setting in hbm file

  1. <cache usage=“read-only” />

3) Create ehcache.xml file

  1. <?xml version=“1.0”?>
  2. <ehcache>
  3. <defaultCache
  4. maxElementsInMemory=“100”
  5. eternal=“true”/>
  6. </ehcache>

Hibernate Second Level Cache Example

To understand the second level cache through example, we need to create following pages:

  2. employee.hbm.xml
  3. hibernate.cfg.xml
  4. ehcache.xml

Here, we are assuming, there is emp1012 table in the oracle database containing some records.

  1. package com.Kreationnext;
  2. public class Employee {
  3. private int id;
  4. private String name;
  5. private float salary;
  6. public Employee() {}
  7. public Employee(String name, float salary) {
  8.     super();
  9. = name;
  10.     this.salary = salary;
  11. }
  12. //setters and getters
  13. }

File: employee.hbm.xml
  1. <?xml version=‘1.0’ encoding=‘UTF-8’?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3.           “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
  4.           “”>
  5.           <hibernate-mapping>
  6.           <class name=“com.Kreationnext.Employee” table=“emp1012”>
  7.           <cache usage=“read-only” />
  8.           <id name=“id”>
  9.           <generator class=“native”></generator>
  10.           </id>
  11.           <property name=“name”></property>
  12.           <property name=“salary”></property>
  13.           </class>
  14.           </hibernate-mapping>

Here, we are using read-only cache usage for the class. The cache usage can also be used in collection.

File: hibernate.cfg.xml
  1. <?xml version=‘1.0’ encoding=‘UTF-8’?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.           “-//Hibernate/Hibernate Configuration DTD 3.0//EN”
  4.           “”>
  5. <!– Generated by MyEclipse Hibernate Tools.                   –>
  6. <hibernate-configuration>
  7.     <session-factory>
  8.         <property name=“show_sql”>true</property>
  9.         <property name=“”>update</property>
  10.         <property name=“dialect”>org.hibernate.dialect.Oracle9Dialect</property>
  11.         <property name=“connection.url”>jdbc:oracle:thin:@localhost:1521:xe</property>
  12.         <property name=“connection.username”>system</property>
  13.         <property name=“connection.password”>oracle</property>
  14.         <property name=“connection.driver_class”>oracle.jdbc.driver.OracleDriver</property>
  15.         <property name=“cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>
  16.          <property name=“hibernate.cache.use_second_level_cache”>true</property>
  17.     <mapping resource=“employee.hbm.xml”/>
  18.     </session-factory>
  19. </hibernate-configuration>

To implement second level cache, we need to define cache.provider_class property in the configuration file.

File: ehcache.xml
  1. <?xml version=“1.0”?>
  2. <ehcache>
  3. <defaultCache
  4. maxElementsInMemory=“100”
  5. eternal=“false”
  6. timeToIdleSeconds=“120”
  7. timeToLiveSeconds=“200” />
  8. <cache name=“com.Kreationnext.Employee”
  9. maxElementsInMemory=“100”
  10. eternal=“false”
  11. timeToIdleSeconds=“5”
  12. timeToLiveSeconds=“200” />
  13. </ehcache>

You need to create ehcache.xml file to define the cache property.

defaultCache will be used for all the persistent classes. We can also define persistent class explicitely by using the cache element.

eternal If we specify eternal=”true”, we don’t need to define timeToIdleSeconds and timeToLiveSeconds attributes because it will be handled by hibernate internally. Specifying eternal=”false” gives control to the programmer, but we need to define timeToIdleSeconds and timeToLiveSeconds attributes.

timeToIdleSeconds It defines that how many seconds object can be idle in the second level cache.

timeToLiveSeconds It defines that how many seconds object can be stored in the second level cache whether it is idle or not.

  1. package com.Kreationnext;
  2. import org.hibernate.Session;
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5. public class FetchTest {
  6. public static void main(String[] args) {
  7. Configuration cfg=new Configuration().configure(“hibernate.cfg.xml”);
  8. SessionFactory factory=cfg.buildSessionFactory();
  9.     Session session1=factory.openSession();
  10.     Employee emp1=(Employee)session1.load(Employee.class,121);
  11.     System.out.println(emp1.getId()+” “+emp1.getName()+” “+emp1.getSalary());
  12.     session1.close();
  13.     Session session2=factory.openSession();
  14.     Employee emp2=(Employee)session2.load(Employee.class,121);
  15.     System.out.println(emp2.getId()+” “+emp2.getName()+” “+emp2.getSalary());
  16.     session2.close();
  17. }
  18. }



As we can see here, hibernate does not fire query twice. If you don’t use second level cache, hibernate will fire query twice because both query uses different session objects.