hibernate second level cache

Posted: April 14, 2012 in Hibernate

Second – Level Cache Using Hibernate:

A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database and put it whether in memory or in file. Database access is necessary only when retrieving data that is not currently available in the cache. So basically not all queries are taken from database, but from cache instead.

1)        Create a table in database named as products

CREATE TABLE `products` (

`pid` int(4) NOT NULL AUTO_INCREMENT,

`pname` varchar(25) DEFAULT NULL,

`price` double DEFAULT NULL,

PRIMARY KEY (`pid`)

) ENGINE=InnoDB AUTO_INCREMENT=107 DEFAULT CHARSET=latin1

Insert values into products(1,”gopal”,5000)

Insert values into products(2,”satya”,6000)

2)       Create pojo class in our project

         package com.shal;

        public class Product {

private int productId;

private String proName;

private double price;

//setters and getters

}

3)       Create hibernate.cfg.xml as usual

<hibernate-configuration>

<session-factory>

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

<property name=”connection.url”>jdbc:mysql://localhost/gopal</property>

<property name=”connection.username”>root</property>

<property name=”connection.password”>shal</property>

<!—we hv to tell hibernate that we wanted to use second level cache

Here I am using one of the hibernate cache like EhCacheProvider –>

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

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

<!—show_sql true is needed whether the query hitting database for every time —>

<property name=”show_sql”>true</property>

<property name=”hbm2ddl.auto”>update</property>

<mapping resource=”Product.hbm.xml”></mapping>

</session-factory>

</hibernate-configuration>

4)       Create ecache.xml (its new)

<?xml version=”1.0″ encoding=”UTF-8″?>

<ehcache>

<defaultCache maxElementsInMemory=”100″ eternal=”false” timeToIdleSeconds=”120″ timeToLiveSeconds=”200″ />

<cache name=”com.shal.Product” maxElementsInMemory=”100″ eternal=”false” timeToIdleSeconds=”5″ timeToLiveSeconds=”200″ />  </ehcache>

<ehcache>

<diskStore path=”java.io.tmpdir”/>                    (1)

<defaultCache

maxElementsInMemory=”10000″                       (2)

eternal=”false”                                                          (3)

timeToIdleSeconds=”120″                                    (4)

timeToLiveSeconds=”120″                                   (5)

overflowToDisk=”true”                                          (6)

/>

</ehcache>

diskStore : Sets the path to the directory where cache .data files are created. The following properties are translated:

a.user.home – User’s home directory

b.user.dir – User’s current working directory

c.java.io.tmpdir (Default temp file path)

maxElementsInMemory : Sets the maximum number of objects that will be created in memory.

eternal : Sets whether elements are eternal. If eternal,  timeouts are ignored and the element is never expired.

timeToIdleSeconds : Sets the time to idle for an element before it expires. Is only used if the element is not eternal. Idle time is now – last accessed time.

timeToLiveSeconds : Sets the time to live for an element before it expires. Is only used if the element is not eternal. TTL is now – creation time

  • overflowToDisk : Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit.

Finally the cache concurrency strategy has to be specified in mapping files. For example, the following code fragment shows how to configure your cache strategy

5)       Create product.hbm.xml

<hibernate-mapping>

<class name=”com.shal.Product” table=”products”>

<cache usage=”read-only” /> <!— read-only , read-write …., —>

<id name=”productId” column=”pid”  />

<property name=”proName” column=”pname” length=”10″/>

<property name=”price”/>

</class>

</hibernate-mapping>

6)       Create main

package com.shal;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class EhCacheExample {

public static void main(String[] args)

{

Configuration cfg = new Configuration();

cfg.configure(“hibernate.cfg.xml”);

SessionFactory factory = cfg.buildSessionFactory();

Session session1 = factory.openSession();

Object o=session1.load(Product.class,new Integer(105));

Product s=(Product)o;

System.out.println(“Loaded object product name is___”+s.getProName());

System.out.println(“Object Loaded successfully…..!!”);

session1.close();

System.out.println(“——————————“);

System.out.println(“Waiting……”);

try{

Thread.sleep(6000);

}

catch (Exception e) {

}

System.out.println(“6 seconds compelted……!!!!!!!!”);

Session session2 = factory.openSession();

Object o2=session2.load(Product.class,new Integer(105));

Product s2=(Product)o2;

System.out.println(“Loaded object product name is___”+s2.getProName());

System.out.println(“Object loaded from the database…!!”);

session2.close();

Session session3 = factory.openSession();

Object o3=session3.load(Product.class,new Integer(105));

Product s3=(Product)o3;

System.out.println(“Loaded object product name is___”+s3.getProName());

System.out.println(“Object loaded from global cache successfully…..!!”);

session3.close();

factory.close();

}

}

Output:

Hibernate: select product0_.pid as pid0_0_, product0_.pname as pname0_0_, product0_.price as price0_0_ from products product0_ where product0_.pid=?

Loaded object product name is___BC

Object Loaded successfully…..!!

——————————

Waiting……

6 seconds compelted……!!!!!!!!

Hibernate: select product0_.pid as pid0_0_, product0_.pname as pname0_0_, product0_.price as price0_0_ from products product0_ where product0_.pid=?

Loaded object product name is___BC

Object loaded from the database…!!

Loaded object product name is___BC

Object loaded from global cache successfully…..!!

Project Structure:

MyProject

src

com.shal

EhCacheExample.java

Product.java

hibernate.hbm.xml

product.hbm.xml

ehcache.xml

Used jar files:

 

mysql-connector-java-3.1.12-bin.jar

antlr-2.7.6.jar

asm.jar

cglib-2.1_3.jar

commons-collections-2.1.1.jar

commons-logging-1.0.4.jar

dom4j-1.6.1.jar

ehcache-1.2.3.jar

hibernate-3.2.6.ga.jar

jta.jar

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s