Saturday, 27 December 2014

Hibernate Second Level cache Demonstration


 Here we demonstrate the second level cache of hibernate using ehcache.Here in this example we are using one entity student and READ_ONLY cache strategy to handle cache.


 StudentInfo.java

package com.nik.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name = "student")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY,region="studentCache")

public class StudentInfo implements java.io.Serializable {
   @Id
   @GeneratedValue
   @Column(name = "student_id")
    private long studentId;

   @Column(name = "student_name")
    private String studentName;

    public StudentInfo() {
    }

    public StudentInfo(String studentName) {
        this.studentName = studentName;
    }

    public long getStudentId() {
        return this.studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return this.studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

}

Hibernate configuration file is as follows:

hibenate.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 name="">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost/testdb</property>
  <property name="hibernate.connection.username">root</property>
  <property name="connection.password">*********</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hbm2ddl.auto">create</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
              
         <!-- enable second level cache and query cache -->
         <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>
  <mapping class="com.nik.model.StudentInfo" />
   
 </session-factory>
</hibernate-configuration>



ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
    monitoring="autodetect" dynamicConfig="true">

    <diskStore path="java.io.tmpdir/ehcache" />

    <defaultCache maxEntriesLocalHeap="10000" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
        maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU" statistics="true">
        <persistence strategy="localTempSwap" />
    </defaultCache>

    <cache name="studentCache" maxEntriesLocalHeap="10000" eternal="false"
        timeToIdleSeconds="5" timeToLiveSeconds="10">
        <persistence strategy="localTempSwap" />
    </cache>

    <cache name="org.hibernate.cache.internal.StandardQueryCache"
        maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
        <persistence strategy="localTempSwap" />
    </cache>

</ehcache>

HibernateUtil.java

package com.nik.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {
  
    private static SessionFactory sessionFactory;
  
     private static SessionFactory buildSessionFactory() {
            try {
                // Create the SessionFactory from hibernate.cfg.xml
                Configuration configuration = new Configuration();
                configuration.configure("hibernate.cfg.xml");
                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
                SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
                return sessionFactory;
            }
            catch (Throwable ex) {
                System.err.println("SessionFactory creation failed." + ex);
                ex.printStackTrace();
                throw new ExceptionInInitializerError(ex);
            }
        }
       
        public static SessionFactory getSessionFactory() {
            if(sessionFactory == null) sessionFactory = buildSessionFactory();
            return sessionFactory;
        }
}


StudentServiceImpl.java

package com.nik.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.nik.model.StudentInfo;
import com.nik.util.HibernateUtil;

public class StudentServiceImpl {
    public static void main(String[] arg){
         SessionFactory sf = HibernateUtil.getSessionFactory(); 
         Session session = sf.openSession(); 
          
         session.beginTransaction(); 
          
         StudentInfo student = new StudentInfo(); 
         student.setStudentName("Nitesh Sahay");
          
             
         session.save(student); 
          
         session.getTransaction().commit(); 
         StudentInfo stu=(StudentInfo) session.load(StudentInfo.class, 1l);
         System.out.println(stu.getStudentName());
         session.close();
         session = sf.openSession();
         session.evict(stu); //evict student from 1st level cache if any
         session.clear();//clear 1st level cache
         stu=(StudentInfo) session.load(StudentInfo.class, 1l);
        
         System.out.println(stu.getStudentName());
        
         System.out.println(stu.getStudentName());
         session.close();
         sf.close();
        }



}

Output:




Saturday, 13 December 2014

Hibernate First Level cache Example

Hibernate first level cache is available to the same valid hibernate session . So it means all the objects which are in persistent state are available in first level cache until and unless the session is clear or objects are evicted from the session.Hibernate by default provide the First level cache . Here is the live example to explain the fact.

Using the previous  posted example... http://hibernate4us.blogspot.in/2012/12/simple-hibernate-example-here-i-am.html

FirstLevelCacheIlluastrationClass.java

public class FirstLevelCacheIlluastrationClass {
public static void main(String[] arg){
 Configuration configuration = new Configuration();
     SessionFactory    sessionFactory =configuration.buildSessionFactory();
    Session session=sessionFactory.openSession();
    Transaction tx=null;
    tx.beginTransaction();
    StudentClass stuObject=new StudentClass();
    stuObject.setStudentName("Nitesh Sahay");
    String studentId=session.save(stuObject);
    tx.commit();

    stuObject=null;
    stuObject=session.load(StudentClass.class,studentId);;//Able to get the student //from First level cache
    System.out.println(stuObject.getStudentName());
    session.close();
    try{
         System.out.println(stuObject.getStudentName());
}catch(Exception e){
   e.printStackTrace();//session already closed... no proxy
}

}
}