Thursday, April 28, 2016

First level Caching in Hibernate and Hibernate Example 8

Caching in Hibernate

By default, hibernate provides the First level caching which means that same queries within the same session won’t hit the DB instantly.

First Level Caching - Within the same session
Second Level Caching- Withing different session also.
Third Level Caching- Within different application also.

public class HibernateTestCache {

      public static void main(String[] args) {
           
          SessionFactory sessionFactory = new                                      Configuration().configure().buildSessionFactory();
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            // First level cache is by default there in Hibernate..
            // Second query is already cached and thus hibernate doesn't             hit DB
            Person person=(Person) session.get(Person.class, 1L);
            Person person3=(Person) session.get(Person.class, 1L);
            session.getTransaction().commit();
            session.close();
     
      }
}

Output:

Hibernate: select person0_.id as id0_0_, person0_.name as name0_0_ from PERSON person0_ where person0_.id=?

public class HibernateTestCache {

      public static void main(String[] args) {
           
          SessionFactory sessionFactory = new                                      Configuration().configure().buildSessionFactory();
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            // First level cache is by default there in Hibernate..
            // When session is closed, hibernate will hit DB again
               even for the same query.
            Person person=(Person) session.get(Person.class, 1L);
            session.getTransaction().commit();
            session.close();
           
            // New session is created ,thus person object is lost from               first level caching and hibernate will hit the DB again...
            Session session2 = sessionFactory.openSession();
            session2.beginTransaction();
            Person person4=(Person) session2.get(Person.class, 1L);
            session2.getTransaction().commit();
            session2.close();
           
      }
}

Output :
Hibernate: select person0_.id as id0_0_, person0_.name as name0_0_ from PERSON person0_ where person0_.id=?
Hibernate: select person0_.id as id0_0_, person0_.name as name0_0_ from PERSON person0_ where person0_.id=?


No comments:

Post a Comment