Monday 11 June 2018

What is a Hibernate Caching ? Explain first level and second level cache in Hibernate

       In previous post, learned the different states of an entity bean in Hibernate.  In this we will learn the caching mechanism and first and second level cache in Hibernate.
        

What is Caching in Hibernate ? 

       Caching is a mechanism for storing the loaded objects into a cache memory.  The advantage of caching mechanism is, whenever again we want to load the same object from the database then instead of hitting the database once again, it loads from the local cache memory only, so that the no. of round trips between an application and a database server got decreased.  It increases the performance of the application.

There are mainly two types of caching:-
  •  First Level Cache 
  •  Second Level Cache.     


First Level Cache:-

        First level cache is associated with “session” object. The scope of cache objects is of  session. Once session is closed, cached objects are gone forever.
       First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

Example:--
    
       In this example, I am retrieving Department object from database using hibernate session.
I will retrieve it multiple times, and will observe the sql logs to see the differences.

//Open the hibernate session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
 
//fetch the department entity from database first time
Department department = (Department) session.load(Department.class, new Integer(1));
System.out.println(department.getName());
 
//fetch the department entity again(second time)
department = (Department) session.load(Department.class, new Integer(1));
System.out.println(department.getName());
 
session.getTransaction().commit();
HibernateUtil.shutdown();
 


Output:

Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
IT
IT

evict() and clear() method in Hibernate:-

evict():  Removes the object from the session. This method is used to dissociate/disconnect the specified object from the session.

clear () :  When this method get called inside transaction boundry then all objects  which are currently associate with particular session will be  disconnected / clean or no longer associate with that Session instance.


Second Level Cache:--

            Second level cache is associated with Session Factory.   It is created in session factory scope and is available to be used in all sessions which are created using that particular session factory. It also means that once session factory is closed, all cache associated with it die and cache manager also closed down.
           Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session). If cached copy of entity is present in first level cache, it is returned as result of load method. If there is no cached entity in first level cache, then second level cache is looked up for cached entity. If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again. If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.

           Second Level Cache is not enabled by default, there are different vendors provided the implementation of Second Level Cache,

  • EH Cache
  • OS Cache
  • Swarm Cache
  • JBoss Cache

           Each implementation provides different cache usage functionality. There are four ways to use second level cache.

read-only:  caching will work for read only operation.

nonstrict-read-write: caching will work for read and write but one at a time.

read-write: caching will work for read and write, can be used simultaneously.

transactional: caching will work for transaction.


Example :--
     
     In the below example, we are using EH Cache provider implementation of Second Level Cache.

hibernate.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>  
        <property name="show_sql">true</property>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
        <property name="connection.url">jdbc:mysql://localhost/sample</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">root</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
        
        <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
        <property name="hibernate.cache.use_second_level_cache">true</property>  
       
    </session-factory>  
  
</hibernate-configuration>

SampleTest.java,

package com.adnblog;  
  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;  
  
public class SampleTest {  
     public static void main(String[] args) {  
          Configuration cfg=new Configuration().configure("hibernate.cfg.xml");  
          SessionFactory factory=cfg.buildSessionFactory();  
      
          Session session1=factory.openSession();  
          Student std1=(Student)session1.load(Student.class,121);  
          System.out.println(std1.getId()+" "+std1.getName());  
          session1.close();  
      
          Session session2=factory.openSession();  
          Student std2=(Student)session2.load(Student.class,121);  
          System.out.println(std2.getId()+" "+std2.getName());  
          session2.close();  
      
     }  
}  
  
Output :--  select student0_.id as id0_0, student0_.name as name0_0 from STUDENT student0_ where student0_.id = ?
                   18 Mahesh M
                   18 Mahesh M

Thank you for visiting blog.


Related Post:-
1) What are different states of an entity bean in Hibernate?
2) Hibernate One to One Mapping Example - Annotation based
3) Hibernate - JPA Annotations with explanation
4) Advantages of Hibernate over JDBC
5) What are the Core Interfaces of Hibernate framework ?
6) Spring MVC with Hibernate CRUD Example

No comments:

Post a Comment