Ehcache with Hibernate

Simple application that just get some records via Hibernate from database and add these records to cache which supplied by EhCache.

There is “Contact” table in database which includes ID, NAME and ADDRESS values.

“Contact” class for mapping this table:

package com.ehcache;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name = "Contact")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "contact_region")
public class Contact {

	@Id
	@Column(name = "ID", unique = true, nullable = false)
	private int id;

	@Column(name = "NAME")
	private String name;

	@Column(name = "ADDRESS")
	private String address;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Contact [ID=").append(id).append(", NAME=")
				.append(name).append(", ADDRESS=").append(address).append("]");
		return builder.toString();
	}

}

HibernateUtil.class for initial operations:

package com.ehcache;

import java.io.File;
import java.io.Serializable;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	private static SessionFactory sessionFactory = buildSessionFactory();
	private static ServiceRegistry serviceRegistry;

	private static SessionFactory buildSessionFactory() {
		try {
			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new StandardServiceRegistryBuilder()
					.applySettings(configuration.getProperties()).build();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
			return sessionFactory;

		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void closeSession() {
		getSessionFactory().close();
	}
}

Main.class:

package com.ehcache;

import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.hibernate.Query;
import org.hibernate.Session;

public class Main {

	public static void main(String[] args) {
		//generateTestData();

		try {
			CacheManager manager = CacheManager.create();
			Cache cache = manager.getCache("contact_region");

			//first get records from DB
			long dbStart = System.currentTimeMillis();
			Session session1 = HibernateUtil.getSessionFactory().openSession();
			session1.beginTransaction();
			Query query = session1.createQuery("from Contact").setMaxResults(10000);
			List<Contact> list = query.list();

			for (int i = 0; i < 10000; i++) {
				Contact ct = new Contact();
				ct = list.get(i);
				Element e = new Element(i, ct);
				cache.put(e);
			}

			session1.getTransaction().commit();
			session1.close();
			System.out.println("From DB: " + (System.currentTimeMillis() - dbStart));
			
			//this time hibernate get records from level 2 cache instead of DB, so it is faster
			long l2cStart = System.currentTimeMillis();
			Session session2 = HibernateUtil.getSessionFactory().openSession();
			session2.beginTransaction();
			for (int i = 0; i < 10000; i++) {
				Contact ct2 = (Contact) session2.load(Contact.class, i);
			}
			session2.getTransaction().commit();
			session2.close();
			System.out.println("From L2Cache: " + (System.currentTimeMillis() - l2cStart));

			//or we can get records from ehcache directly without hibernate, so it is better
			long ehcacheStart = System.currentTimeMillis();
			for (int i = 0; i < 10000; i++) {
				Element e = cache.get(i);
				//System.out.println("i: " + e.getObjectKey() + " object: " + e.getObjectValue());
			}
			System.out.println("From ehcache: " + (System.currentTimeMillis() - ehcacheStart));

			//System.out.println("cache.getSize: " + cache.getSize());
			//System.out.println("cache.getName: " + cache.getName());

		} finally {
			HibernateUtil.closeSession();
		}

	}

	//in your first run this function create test data in db
	//but you should "hbm2ddl.auto" parameter set as "create" in hibernate.cfg.xml 
	private static void generateTestData() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();

		for (int i = 0; i < 10000; i++) {
			Contact ct = new Contact();
			ct.setId(i);
			ct.setName("name_" + i);
			ct.setAddress("address_" + i);
			session.save(ct);
		}

		session.getTransaction().commit();
		session.close();
	}

}

hibernate.cfg.xml:

<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>        
		<property name="hbm2ddl.auto">update</property>
		<property name="hibernate.generate_statistics">false</property>
				
		<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
		<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
        <property name="hibernate.cache.use_second_level_cache">true</property>

        <mapping class="com.ehcache.Contact"></mapping>

    </session-factory>
</hibernate-configuration>

ehcache.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
	<cache name="contact_region" eternal="true" />
</ehcache>

Package Explorer:
ehcache

References:
http://howtodoinjava.com/2013/07/04/hibernate-ehcache-configuration-tutorial/
http://stackoverflow.com/questions/8621906/is-buildsessionfactory-deprecated-in-hibernate-4
http://hibernate.org/orm/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: