This tutorial will sow how we can configure second level cache using ehcache in Hibernate step by step. EH stands for Easy Hibernate. We know that tehre are three types of caching mechanism such as First Level – session, Second Level – SessionFactory and Query Level – SessionFactory.

For more information on First Level, Second Level and Query Level please go through Hibernate Caching strategy.

Prerequisites

MySQL Database 5.5
JDK 1.6
MySQL Connector jar
Hibernate jars
Hibernate SessionFactory Second Level EHCache example

Create a MySQL table called cd

CREATE TABLE `cd` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) COLLATE latin1_general_ci NOT NULL,
  `artist` varchar(100) COLLATE latin1_general_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

 

Insert some data

insert  into `cd`(`id`,`title`,`artist`) values
(4,'CD Caching','Soumitra'),
(20,'CD Caching','Soumitra'),
(21,'CD Caching','Soumitra'),
(22,'CD Caching','Soumitra');

 

Create POJO and hibernate mapping file for the database table

CD.java

package in.webtuts.domain;

import java.io.Serializable;

/**
 * @author admin
 *
 */
public class CD implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    Long id;
    String title;
    String artist;

    public CD() {
    }

    public CD(Long id, String title, String artist) {
        this.id = id;
        this.title = title;
        this.artist = artist;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

}

 

The above pojo file is simple and easy to use. It just declares the attributes same as in the database table.

mapping file – CD.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="in.webtuts.domain.CD" table="cd" catalog="cdcol">
        <cache usage="read-write" />
        <id name="id" type="java.lang.Long">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="title" type="string">
            <column name="title" length="200" />
        </property>
        <property name="artist" type="string">
            <column name="artist" length="200" />
        </property>
    </class>
</hibernate-mapping>

 

The mapping file is simple and easy to understand. In the above mapping file I have used

<cache usage="read-write" />

 

use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.

Now we need to configure hibernate to connect the database table as well as to use the second level cache for ehcache. Below is the hibernate.cfg.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <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/cdcol?zeroDateTimeBehavior=convertToNull</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.generate_statistics">true</property>
        <property name="hibernate.cache.use_structured_entries">true</property>
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <!-- <property name="hibernate.cache.use_query_cache">true</property> -->
        <!-- <property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property> -->
        <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
        <!-- <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->
        <mapping resource="in/webtuts/domain/CD.hbm.xml" />
    </session-factory>
</hibernate-configuration>

 

I will explain each of the property tag here

Below property denotes what type of Dialect should be used for the database.

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

Below property denotes which driver class should be used based on the database

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

Below is the full database URL with host, port and database instance. zeroDateTimeBehavior=convertToNull will convert ‘0000-00-00 00:00:00’ or ‘0000-00-00’ to null value.

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/cdcol?zeroDateTimeBehavior=convertToNull</property>

 

Below denotes username of the database.

<property name="hibernate.connection.username">root</property>

 

Below denotes password for the database. I don’t have password for my database so I didn’t use this property.

<property name="hibernate.connection.password">root</property>

 

Which session context we should use. Possible values are jta, thread and managed. I use thread.

<property name="hibernate.current_session_context_class">thread</property>

 

Below is the query parser for performing the translation

<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>

 

Show generated sql in the console

<property name="hibernate.show_sql">true</property>

 

Format the generate sql query in the console for better readability

<property name="hibernate.format_sql">true</property>

 

Hibernate gives some useful metrics like Entity Insert/Delete/Load/Fetch count, Query Cache hit/miss/put/get count etc.

<property name="hibernate.generate_statistics">true</property>

 

Force Hibernate to keep the cache entries in a more readable format.

<property name="hibernate.cache.use_structured_entries">true</property>

 

Use below property to use the second level cache in Hibernate.

<property name="hibernate.cache.use_second_level_cache">true</property>

 

Below property denotes that we are using second level cache for EhCache

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

 

This is the mapping xml file to the java object with the database table

<mapping resource="in/webtuts/domain/CD.hbm.xml" />

 

Below property indicates if the ehcache.xml file located in other than classpath location. If you place your ehcache.xml file in the classpath then you don’t need to put this property in the hibernate configuration.

<property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>

 

Nest step is to configure the ehcache.xml file and put it under classpath, i.e., in the src folder.

ehcache.xml looks like below

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <diskStore path="java.io.tmpdir/ehcache" />
    <defaultCache maxElementsInMemory="1000" eternal="false"
        timeToIdleSeconds="3" timeToLiveSeconds="120" overflowToDisk="true" />
    <cache name="in.webtuts.domain.CD" maxElementsInMemory="100" eternal="false"
        timeToIdleSeconds="3" timeToLiveSeconds="120" overflowToDisk="false" />
</ehcache>

 

In this file there are few things to mention –

diskStore: EhCache stores data into memory but when it starts overflowing, it start writing data into file system. We use “path” property to define the location where EhCache will write the overflown data.

defaultCache: It’s a mandatory configuration, it is used when an object need to be cached and there are no caching regions defined for that.

cache name=”in.webtuts.domain.CD”: We use cache element to define the region and its configurations. We can define multiple regions and their properties. While we define model beans cache properties, we can also define region with caching strategies.

In ehcache.xml if eternal=”true” then we should not write timeToIdealSeconds, timeToLiveSeconds because Hibernate will take automatically care about those values. So if you want to give values for timeToIdealSeconds, timeToLiveSeconds then use better eternal=”false” always.

In ehcache.xml timeToIdealSeconds=”seconds” means, if the object in the global chche is idle for sometime, means not using by any other class or object then it will be waited for the time we have specified in timeToIdealSeconds and it will be deleted from the global cache if time is exceeds more than timeToIdealSeconds value.

In ehcache.xml timeToLiveSeconds=”seconds” means the other Session or class using this object or not, whatever the situation occurrs, when the time exceeds timeToLiveSeconds value then it will be removed from the global cache by hibernate.

Now we will create HibernateUtil.java file which will give us the Singleton SessionFactory.

package in.webtuts.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author admin
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
            sessionFactory = new AnnotationConfiguration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

 

The above class is simple and easy to understand.

Next we write the CDTest.java for testing our work.

package in.webtuts.test;

import in.webtuts.domain.CD;
import in.webtuts.utils.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class CDTest {

    public static void main(String[] args) {
        Session sess = null;
        Session dbSession1 = null;
        Session dbSession2 = null;
        Session newSession = null;
        Transaction tran = null;
        Transaction dbTransaction1 = null;
        Transaction dbTransaction2 = null;
        Transaction newTransaction = null;
        System.out.println("Fetch count from DB: "
                + HibernateUtil.getSessionFactory().getStatistics()
                        .getEntityFetchCount());
        System.out.println("Fetch count from second-level session: "
                + HibernateUtil.getSessionFactory().getStatistics()
                        .getSecondLevelCacheHitCount());
        System.out.println("Miss count from second-level session: "
                + HibernateUtil.getSessionFactory().getStatistics()
                        .getSecondLevelCacheMissCount());
        System.out.println("Put count from second-level session:"
                + HibernateUtil.getSessionFactory().getStatistics()
                        .getSecondLevelCachePutCount());
        System.out.println();
        try {
            // save the new CD
            sess = HibernateUtil.getSessionFactory().openSession();
            tran = sess.beginTransaction();
            CD cd = new CD();
            cd.setTitle("CD Caching");
            cd.setArtist("Soumitra");
            sess.save(cd);
            tran.commit();
            sess.close();

            dbSession1 = HibernateUtil.getSessionFactory().openSession();
            dbTransaction1 = dbSession1.beginTransaction();

            // load the CD from database table
            CD cd1 = (CD) dbSession1.load(CD.class, 4l);
            System.out.println("CD Loaded from DB - title: " + cd1.getTitle());
            System.out.println();

            // load the CD from first-level Session
            CD cd2 = (CD) dbSession1.load(CD.class, 4l);
            System.out.println("CD Loaded from First-level session - title: "
                    + cd2.getTitle());
            System.out.println();

            dbTransaction1.commit();
            dbSession1.close();

            System.out.println("Fetch count from DB: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getEntityFetchCount());
            System.out.println("Fetch count from second-level session: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCacheHitCount());
            System.out.println("Miss count from second-level session: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCacheMissCount());
            System.out.println("Put count from second-level session:"
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCachePutCount());
            System.out.println();

            System.out.println("Waiting........");
            System.out.println();
            Thread.sleep(5000);

            dbSession2 = HibernateUtil.getSessionFactory().openSession();
            dbTransaction2 = dbSession2.beginTransaction();

            // load the CD from Database
            CD cd3 = (CD) dbSession2.load(CD.class, 4l);
            System.out.println();
            System.out.println("Again Loaded CD from DB - title: "
                    + cd3.getTitle());
            System.out.println();

            dbTransaction2.commit();
            dbSession2.close();

            System.out.println("Fetch count from DB: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getEntityFetchCount());
            System.out.println("Fetch count from second-level session: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCacheHitCount());
            System.out.println("Miss count from second-level session: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCacheMissCount());
            System.out.println("Put count from second-level session:"
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCachePutCount());
            System.out.println();

            newSession = HibernateUtil.getSessionFactory().openSession();
            newTransaction = newSession.beginTransaction();

            // we have already second-level of cache for the CD
            CD cd4 = (CD) newSession.get(CD.class, 4l);
            System.out.println("CD loaded from Second-level - title: "
                    + cd4.getTitle());
            System.out.println();
            newTransaction.commit();
            newSession.close();

            System.out.println("Fetch count from DB: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getEntityFetchCount());
            System.out.println("Fetch count from second-level session: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCacheHitCount());
            System.out.println("Miss count from second-level session: "
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCacheMissCount());
            System.out.println("Put count from second-level session:"
                    + HibernateUtil.getSessionFactory().getStatistics()
                            .getSecondLevelCachePutCount());
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
            if (tran != null && sess.isOpen()) {
                tran.rollback();
            }
            if (dbTransaction1 != null && dbSession1.isOpen()) {
                dbTransaction1.rollback();
            }
            if (dbTransaction2 != null && dbSession2.isOpen()) {
                dbTransaction2.rollback();
            }
            if (newTransaction != null && newSession.isOpen()) {
                newTransaction.rollback();
            }
        } finally {
            HibernateUtil.getSessionFactory().close();
        }
    }

}

 

Note that for a cached query, the cache miss is equals to the db count

Once you run the CDTest.java then you will see the following output

Fetch count from DB: 0
Fetch count from second-level session: 0
Miss count from second-level session: 0
Put count from second-level session:0

Hibernate:
    select
        cd0_.id as id0_0_,
        cd0_.title as title0_0_,
        cd0_.artist as artist0_0_
    from
        cdcol.cd cd0_
    where
        cd0_.id=?
CD Loaded from DB - title: CD Caching

CD Loaded from First-level session - title: CD Caching

Fetch count from DB: 1
Fetch count from second-level session: 0
Miss count from second-level session: 1
Put count from second-level session:1

Waiting........

Hibernate:
    select
        cd0_.id as id0_0_,
        cd0_.title as title0_0_,
        cd0_.artist as artist0_0_
    from
        cdcol.cd cd0_
    where
        cd0_.id=?
Again Loaded CD from DB - title: CD Caching

Fetch count from DB: 2
Fetch count from second-level session: 0
Miss count from second-level session: 2
Put count from second-level session:2

CD loaded from Second-level - title: CD Caching

Fetch count from DB: 2
Fetch count from second-level session: 1
Miss count from second-level session: 2
Put count from second-level session:2

 

I will explain here about the output.

1. First we get the below statistics and all are 0 because we don’t have any Session, Transaction etc.

Fetch count from DB: 0
Fetch count from second-level session: 0
Miss count from second-level session: 0
Put count from second-level session:0

 

2. Then we save one CD entity because we have to test with this entity. We open the “dbSession1” and start the transaction “dbTransaction1”. Then we load “cd1” entity from the database as the database has been hit for loading the data.

Hibernate:
    select
        cd0_.id as id0_0_,
        cd0_.title as title0_0_,
        cd0_.artist as artist0_0_
    from
        cdcol.cd cd0_
    where
        cd0_.id=?
CD Loaded from DB - title: CD Caching

 

Then “cd2” entity is loaded from the first level session because in this case database was not hit and session was also not closed while fetching the data as it is clear from the below output.

CD Loaded from First-level session - title: CD Caching

 

So here we get the below statistics

Fetch count from DB: 1
Fetch count from second-level session: 0
Miss count from second-level session: 1
Put count from second-level session:1

 

All have obvious meaning. Note that the cache miss is equal to the db count. Put count is the count of storing the data in cache.

Whenever the data is stored in first level then the data is also stored in the second level cache.

Note we need to close the Session after each transaction for getting the obvious output.

3. If you look at ehcahe.xml we have timeToIdleSeconds=”3″ so, it means after 3 idle seconds the session gets expired.
Now if you look carefully at CDTest.java file then you will find Thread.sleep(5000) so we are here waiting for 5 seconds and it is obvious that the second level cache must expire by this time. So we get the below output after “Waiting….” for “cd3” entity.

Hibernate:
    select
        cd0_.id as id0_0_,
        cd0_.title as title0_0_,
        cd0_.artist as artist0_0_
    from
        cdcol.cd cd0_
    where
        cd0_.id=?
Again Loaded CD from DB - title: CD Caching

Fetch count from DB: 2
Fetch count from second-level session: 0
Miss count from second-level session: 2
Put count from second-level session:2

 

So the above output is obvious and “db count”, “miss count”, “put count” have been increased by 1.

4. Now we load the “cd4” entity and get the below output

CD loaded from Second-level - title: CD Caching

Fetch count from DB: 2
Fetch count from second-level session: 1
Miss count from second-level session: 2
Put count from second-level session:2

 

In the above output db count, miss count and put count are same but fetch count has been increased by 1 because we have got this entity from the second level cache.

How do we know that it is coming from second level cache ?

We had opened new session and started new transaction for fetching this “cd4” entity.

Thanks for your reading. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

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