Table of contents
1.
Introduction
2.
Second Level Cache
3.
Importance of Second Level Cache
4.
Example of Hibernate Second Level Cache
4.1.
Create the persistent class using Maven
4.2.
In the pom.xml file, adding project information and configuration
4.3.
Create the configuration file
4.4.
Create the class that retrieves the persistent object.
5.
Use of Second Level Cache in Hibernate
6.
Frequently Asked Questions
6.1.
Is second-level caching mandatory in Hibernate?
6.2.
How many levels of cache are there in Hibernate?
6.3.
What is the disadvantage of 2nd level cache?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Second Level Cache in Hibernate

Author Sagar Mishra
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The ability of database abstraction layers is ORM (Object Relational Mapping) frameworks. Transparently cache data retrieved from the underlying store is one of their benefits. This reduces the expense of database access for frequently sought data.

In this blog, we will explore Second Level Cache in Hibernate. We will learn basic concepts with simple instances.

Second Level Cache

You can connect a caching technology to the Second Level Cache in Hibernate to work with the First level cache. The Second Level Cache in Hibernate is checked if the results of the requested query are not already in the First level cache. 

Second level Cache

The Second level cache distributes cached data around sessions so that all sessions and users can take advantage of the data. Even if it was added by another session or the session that added the data to the second-level cache terminates.

Many vendors have provided the implementation of Second Level Cache in Hibernate.

  1. EH Cache
  2. OS Cache
  3. Swarm Cache
  4. JBoss Cache
     

Each implementation gives different cache usage functionality. A Second level cache can be used in four different ways.

Implementation of Cache

Importance of Second Level Cache

  • All sessions created using the same session factory perform better in terms of persistence using a Second Level Cache. 
     
  • A Second Level Cache can fulfill a request for an object with far less delay than if the request went to the database, even if it is done from numerous sessions. 
     
  • A system might considerably benefit from a second-level cache to lessen the repetition of the same slow queries to the underlying database because ORM queries can be complex and quite slow.
     
  • This is helpful for web applications with high user adoption rates.
     
  • It frequently performs SQL queries to access databases.
     
  • You can cache more data and experience more speed acceleration with highly scalable caches.

Example of Hibernate Second Level Cache

There are mainly four steps to understanding Hibernate Second Level Cache. We will understand it all one by one.

Create the persistent class using Maven

import javax.persistence.*;  
import org.hibernate.annotations.Cache;  
import org.hibernate.annotations.CacheConcurrencyStrategy;  
@Entity  
@Table(name="emp1012")  
@Cacheable  
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)  

public class Employee {    
    @Id  
  private int id;    
  private String name;    
  private float salary;    
    
  public Employee() {}    
  public Employee(String name, float salary) {    
      super();    
      this.name = name;    
      this.salary = salary;    
   }  

  public int getId() {  
      return id;  
   }  

  public void setId(int id) {  
      this.id = id;  
   }  

  public String getName() {  
     return name;  
   } 
 
  public void setName(String name) {  
     this.name = name;  
   }  

  public float getSalary() {  
     return salary;  
   }  
  
  public void setSalary(float salary) {  
     this.salary = salary;  
   }    
} 

In the pom.xml file, adding project information and configuration

Click source in the pom.xml file after opening. Add the below dependencies between the tags dependencies> and /dependencies>.

<dependency>  
    <groupId>org.hibernate</groupId>  
    <artifactId>hibernate-core</artifactId>  
    <version>5.2.16.Final</version>  
</dependency>  
      
<dependency>  
    <groupId>com.oracle</groupId>  
    <artifactId>ojdbc14</artifactId>  
    <version>10.2.0.4.0</version>  
</dependency>  


<dependency>  
    <groupId>net.sf.ehcache</groupId>  
    <artifactId>ehcache</artifactId>  
    <version>2.10.3</version>  
</dependency>  


<dependency>  
    <groupId>org.hibernate</groupId>  
    <artifactId>hibernate-ehcache</artifactId>  
    <version>5.2.16.Final</version>  
</dependency>  

Create the configuration file

<?xml version='1.0' encoding='UTF-8'?>    
<!DOCTYPE hibernate-configuration PUBLIC    
          "-//Hibernate/Hibernate Configuration DTD 5.2.0//EN"    
          "http://hibernate.sourceforge.net/hibernate-configuration-5.2.0.dtd">    
    
<hibernate-configuration>    
    
    <session-factory>    
        <property name="show_sql">true</property>    
        <property name="hbm2ddl.auto">update</property>    
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>    
        <property name="connection.username">system</property>    
        <property name="connection.password">jtp</property>    
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>    
         
         <property name="cache.use_second_level_cache">true</property>   
         <property name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>  
         <mapping class="com.codingninjas.Employee"/>  
    </session-factory>    
</hibernate-configuration>

We need to define cache.provider_class property in the configuration file to implement Second level cache in Hibernate.

Create the class that retrieves the persistent object.

This is the last step of the example where we will create the class that retrieves the persistent object.

import org.hibernate.Session;    
import org.hibernate.SessionFactory;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
    
public class FetchTest {    
public static void main(String[] args) {    
    StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
    Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
      
    SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        
    Session session1=factory.openSession();    
    Employee emp1=(Employee)session1.load(Employee.class,121);    
    System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());    
    session1.close();    
        
    Session session2=factory.openSession();    
    Employee emp2=(Employee)session2.load(Employee.class,121);    
    System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());    
    session2.close();    
        
  }    
} 

 

Output

Output image

Hibernate does not fire a query more than once, as we can see here. Hibernate will fire a query twice if you don't use Second level caching since each query uses a distinct session object.

Use of Second Level Cache in Hibernate

  • Any technology that allows Hibernate out-of-the-box integration may be used as a second-level cache. 
     
  • As a Hibernate Second level cache, in-memory data grids are frequently used. 
     
  • Hazelcast IMDG has built-in Hibernate integration that makes it simple to add second-level caching.
     
  • Because of its distributed architecture, you can expand the cluster's cache as much as you'd like to support greater workloads.

Frequently Asked Questions

Is second-level caching mandatory in Hibernate?

A Second Level Cache is an optional addition to this caching. The first level continues to be required and is always consulted first. Objects are cached in the Second Level Cache between sessions. A few third-party products can be utilized with Hibernate for second-level caching. 

How many levels of cache are there in Hibernate?

Hibernate provides two levels of caching: The session cache is the First Level Cache. During the current session, objects are cached and remain active just until the session is ended. As long as the session factory is active, the Second Level Cache is present.

What is the disadvantage of 2nd level cache?

Performance degrades. Yes, you can improve performance without having caching. For the cache to be stored and updated, Hibernate must take further steps. Enabling the cache will only add useless extra work if the entities being cached change often and you don't frequently query them.

Conclusion

We have discussed the topic of Second Level Cache in Hibernate. We have seen the Importance, Dependencies, and configuration of Second Level Cache in Hibernate. Along with this, we have discussed some uses also.

We hope this blog has helped you enhance your knowledge of Hibernate Caching. If you want to learn more, check out our articles What is HibernateHibernate Life CycleHibernate Sessions, and many more on our platform Coding Ninjas Studio.

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Thankyou image

Live masterclass