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

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 Hibernate, Hibernate Life Cycle, Hibernate 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 problems, interview experiences, and interview bundle for placement preparations.
However, you may consider our paid courses to give your career an edge over others!
Happy Learning!
