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;

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

	@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) { = id;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getAddress() {
		return address;

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

	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 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();
			serviceRegistry = new StandardServiceRegistryBuilder()
			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() {


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) {

		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();
			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);

			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();
			for (int i = 0; i < 10000; i++) {
				Contact ct2 = (Contact) session2.load(Contact.class, i);
			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 {


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

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




<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        <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="">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>



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

Package Explorer:


Leave a Reply

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

You are commenting using your 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: