Saturday, April 4, 2015

Hibernate second level cache example



Hibernate Second Level Cache

Hibernate second level cache is used to boost the application formance by minimizing database hit.
Hibernate automatically manage first level cache using session. Now here I will use second level  chache using EHCache.

To configure second level hibernate EHCache follow the following steps:-
1.   Hibernate.cfg.xml configuration for enabling cache
<hibernate-configuration>

    <session-factory>
        <!-- <property name="hbm2ddl.auto">update</property> -->
       <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="connection.url">jdbc:postgresql://localhost:5432/test</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">admin</property>
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="show_sql">true</property>
       <property name="cache.provider_class">org.hibernate.cache.EHCacheProvider</property> 
      <property name="hibernate.cache.use_second_level_cache">true</property> 
      <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
         <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.pojo.User"/>
        <mapping class="com.pojo.Employee"/>
   
    </session-factory>

</hibernate-configuration>
2.   Mapping POJO of User

@javax.persistence.Entity(name="userdetails")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class User implements Serializable {
         
          private static final long serialVersionUID = 1L;
          private Integer userId;
          private String name;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
          public Integer getUserId() {
                   return userId;
          }
          public void setUserId(Integer userId) {
                   this.userId = userId;
          }
          @Column(name="name")
          public String getName() {
                   return name;
          }
          public void setName(String name) {
                   this.name = name;
          }
          }

3.   Configure the User pojo in ehcache.xml file

<?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">
<defaultCache  
maxElementsInMemory="100"  
eternal="false"  
timeToIdleSeconds="120"  
timeToLiveSeconds="200" /> 
 
  <cache name="User"  maxElementsInMemory="100" eternal="false" timeToIdleSeconds="500" timeToLiveSeconds="1000"
 
  />
 
</ehcache>

4.   UserDAO to fetch all user list.
In followng ways we can apply cache in query as well as in Criteria.

public List getUsers()
            {
            List userlist=null;
            Session session=HibernateSessionFactory.getSession();
           

            /*
Set cacheable true when we are using HQL.
Query query=session.createQuery("from com.pojo.User");
            query.setCacheable(true);
            userlist=query.list();*/

//When we fetch data using Criteria set criteria.cacheable true.

            Criteria crit=session.createCriteria(User.class);
            crit.setCacheable(true);
            userlist=crit.list();
           
            session.close();
            return userlist;
      }
5.   Now write the main class to find the list of users.

public static void main(String[] args) {
     
      List userList=new UsersDAO().getUsers();
      System.out.println(userList.size()+" userlist1 records");
     
      List userList2=new UsersDAO().getUsers();
      System.out.println(userList2.size()+" userlist2 records");
      }

OUTPUT
--------------------Calling User List 1st time-----------------------------
Hibernate: select this_.userId as userId0_0_, this_.address as address0_0_, this_.city as city0_0_, this_.hobbies as hobbies0_0_, this_.interest as interest0_0_, this_.isDeleted as isDeleted0_0_, this_.name as name0_0_, this_.state as state0_0_ from userdetails this_

29 userlist1 records
------------------Calling User List 2nd time------------------------------
29 userlist2 records


We have already enabled the show_sql property of hibernate true so now when we call the user list first time it fetch records from the database and print the select query.
But when we call the same user list second time it does not hit the database and fetch the user list from the cache and hibernate does not print and select query on the console.


Note : you can configure your cache to store the data on RAM or in Hard Disk.
 If you want to remove second level cache from the entity you can use the following method to remove it.
            sessionFactory.evictEntity(“User”);

No comments:

Post a Comment

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...