Hibernate Second-Level Cache

The Second-level cache is related to the SessionFactory object. Once the SessionFactory is closed, all the second-level cache data associated with it will be lost. The cache manager will also get closed.

Cache provider

The following are the popular cache providers:

JBoss Cache

It is a transactional and replicated cache. It contains two components, a generic cache, and a POJO cache. It also supports synchronous/asynchronous communication, an optimistic and pessimistic locking. It is available in org.hibernate.cache.TreeCacheProvider package.

EH Cache

EH Cache is a famous open-source Java cache which can be used as a Hibernate second-level cache. Also, it can be used as a standalone second-level cache. It is available in org.hibernate.cache.EhCacheProvider package.

OS Cache

OS Cache is developed by OpenSymphony, which is a Java framework. It can be configured to behave as a second-level cache. It is available in org.hibernate.cache.OSCacheProvider package.

Swarm Cache

Swarm cache is a simple, distributed cache. It internally uses JavaGroups to manage the membership and communications of its distributed cache. It doesn’t support Hibernate query cache. It is available in org.hibernate.cache.SwarmCacheProvider package.

Hashtable

It is not intended for production use. It is only used for testing purpose and available in org.hibernate.cache.HashtableCacheprovider package.   

Concurrency Strategy of Second-level Cache

They act as a mediator, which are responsible for storing data into the cache and fetching data from the cache. There are five concurrency strategies which a user uses when he/she enable the second-level cache. The following are the concurrency strategies:

  1. Read-only
  2. Read-write
  3. Nonstrict read-write
  4. Transactional
  5. None

Read-only

A read-only cache strategy is used for the data which never wants to be changed. It is suitable for the data that needs to be often read but not modified. It is safe and straightforward to use in a clustered environment.

Read-Write

A read-write cache strategy is suitable for an application which needs to be updated regularly. It should never be used if serializable transaction isolation is required. If we want to use this strategy in a cluster, we should check whether the cache implementation supports locking or not.

Nonstrict read-write

If an application is rarely updated (i.e., it is not updated regularly), a nonstrict read-write cache strategy is used. In this strategy, there is no guarantee of consistency between the cache and the database.

Transactional

It provides support for transactional cache providers like JBoss TreeCache. This caching strategy can only be used in a JTA environment, and we must specify a hibernate.transaction.manager_lookup_class.

None

In this strategy, no caching will happen.

Cache concurrency strategy support table

Not all of the cache providers support all cache concurrency strategies. The following table shows which cache provider is compatible with which cache usage functionality.

  Cache Read-only Read-write Nonstrict read-write Transactional
EH Cache          Yes           Yes          Yes           No
OS Cache          Yes           Yes          Yes           No
JBoss Cache          Yes            No           No           Yes
Swarm Cache          Yes            No          Yes           No
Hashtable          Yes           Yes          Yes           No

Example of Second-Level Cache

Let us create an example of the second-level cache. In this example, we are using EH Cache provider to act as a second-level cache. We are assuming that there is an existing table (students) in the database containing some records.

Following are the steps to create an example of Second-level Cache:

  1. Create the POJO class

In this step, we are going to create a POJO class, i.e., Student .java.

Student.java

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name="students")
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="Sid")
private int id;
@Column(name="S_name")
private String name;
@Column(name="S_rno")
private int rollno;
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 int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
} 
  • Add dependencies

In this step, we will add dependencies which are required by the project into pom.xml between the <dependencies>…</dependencies> tag.

 
net.sf.ehcache
ehcache
2.9.1


org.hibernate
hibernate-ehcache
5.4.0.Final
 
  • Create the configuration file.

The configuration file contains the information of mapping class and database.

hibernate.cfg.xml

   
  
  
  
update  
org.hibernate.
dialect.MySQL5Dialect
jdbc:mysql://
localhost:3306/test2
com.mysql.
jdbc.Driver
root  
root   
true
true
           
org.hibernate.
cache.ehcache.EhCacheRegionFactory

  
   
  • Create a class that retrieves the POJO object

It is a class which contains the main() methodused to run the application, and it retrieves the object of the POJO class.

App.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class App 
{
public static void main( String[] args )
{
Configuration cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory fact= cfg.buildSessionFactory();
Session sess= fact.openSession();
sess.beginTransaction();
Student std=  (Student) sess.get(Student.class, 2);   
sess.getTransaction().commit();
sess.close();
System.out.println(std);
//opening a new session
Session sess2= fact.openSession();
sess2.beginTransaction();
Student student=(Student) sess2.get(Student.class, 2);
sess2.getTransaction().commit();
sess2.close();
System.out.println(student);
}
} 

OUTPUT

Hibernate Second-Level Cache

Related Topics

Hibernate First-Level Cache

The first-level cache is related to the Session object. First level cache objects of one Session are not visible to the other Sessions, and all the cache data is lost when the Session...

2 minutes read.

Hibernate Named Query using Annotation

In annotation-based named query, we use @NamedQuery annotation inside the POJO class. @NamedQuery- It is used to describe a single named query. It consists of four attributes- two of which are compulsory, and...

2 minutes read.

Hibernate Composite Primary Key

Hibernate Composite Primary Key A Composite Primary Key is a combination of one or more columns that forms a primary key. When a database table contains more than one primary key column, it is...

8 minutes read.

Hibernate One-to-One Mapping Example

One-to-One Hibernate Mapping In One-to-One association mapping, one object of a persistent class is related to one object of another persistent class. Here, we are going to create an example of one-to-one mapping using...

3 minutes read.

Annotation Example in Hibernate

Hibernate Annotation Example Hibernate is an ORM (Object-Relational Mapping) tool which simplifies the application development. Hibernate provides a framework which interacts with the data stored in the databases, and it also uses...

3 minutes read.

Cascade in Hibernate

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is saved/...

3 minutes read.

Hibernate Session Interface

Hibernate Session Interface A Session is an interface between the Java application and the Hibernate. It is available in the org.hibernate.session package. It should not be kept open for a long time, as it...

4 minutes read.

Hibernate Features

1. Lightweight Hibernate is a lightweight framework as it does not contains additional functionalities; it uses only those functionalities required for object-relational mapping. It is a lightweight framework because it uses persistent...

2 minutes read.

Hibernate Inverse

Hibernate Inverse An Inverse attribute is used to maintain the relationship between the parent and child class object. The inverse attribute is used only with bi-directional mappings such as one-to-many and many-to-many Hibernate mapping. In Hibernate, the...

2 minutes read.

Hibernate N+1 Select Problem

Hibernate N + 1 Select Problem The N + 1 Select problem is a performance issue in Hibernate. In this problem, a Java application makes N + 1 database calls (N = number...

4 minutes read.

Architecture of Hibernate

Next → Hibernate is an ORM framework with a layered architecture. It consists of many objects, such as a persistent object, sessionfactory object, transaction object, session, etc.  There are mainly three layers in Hibernate...

2 minutes read.

Hibernate Criteria Query Language (HCQL)

Hibernate Criteria Query Language (HCQL) is mainly used for searching and fetching records. It works on the filtration rules and logical conditions. The Criteria interface, Restriction class, and Order class are available in...

4 minutes read.

Hibernate merge() vs. update()

In Hibernate, both update() and merge() methods are used to convert the detached state object into the persistent state. session.merge() The merge() method is used when we want to change a detached entity into...

2 minutes read.

Hibernate Inheritance - Single Table

Hibernate Inheritance In this inheritance strategy, only one table is created for all the classes involved in the hierarchy with an additional column known as a discriminator column. The discriminator column helps indifferentiating between...

3 minutes read.

Hibernate Web Application Example

Web Application Example with Hibernate In this section, we create a hibernate web Application. Here we are using a JSP file for presentation. Example of creating a web application using hibernate index.jsp This page will show a...

2 minutes read.

Hibernate Configuration Properties

Hibernate Configuration Hibernate Configuration is a Java class, which allows a Java application to specify configuration parameters used in the application. As Hibernate is designed to serve in different environments, it needs a broad...

6 minutes read.

Hibernate Caching

What is Caching? Caching is a process of saving data into the cache memory. A cache is a temporary storage layer which is used to increase the speed of data access. It allows...

2 minutes read.

Hibernate One-to-Many Mapping

One-to-Many Hibernate Mapping Example In One-to-many association mapping, only one object of a persistent class is related to many objects of another persistent class. It is a relationship in which one (parent) is related...

3 minutes read.

Hibernate save() vs persist()

Session.save() The session.save() method is used to save the transient object by assigning a generated value or using a current value of the identifier property. In other words, the save() method is used...

3 minutes read.

Hibernate Merge

Hibernate Merge Merge is a method available in Hibernate which is used to update the existing records. However, it creates a copy from the passed entity objects and returns it. In other words, the merge()...

2 minutes read.