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
}

}
}



No comments:

Post a Comment