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 Tutorial

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

3 minutes read.

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...

5 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.

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 SessionFactory

Next → Hibernate SessionFactory A SessionFactory is an interface in Hibernate that create the instances of Session interface. It is a heavy weight object, and it is usually created during the application...

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 Lifecycle

Hibernate Lifecycle In Hibernate, the mapped instances of the entity classes have a lifecycle. Either we can create a new object, or we can fetch the existing data from the database. The value objects do...

3 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 Query Language (HQL)

Hibernate provides its query language called Hibernate Query Language (HQL). HQL is an object-oriented query language, similar to the native SQL language, and it works with persistent objects. It is a database-independent and...

2 minutes read.

Lazy Loading in Hibernate

Lazy loading is a fetching technique used for all the entities in Hibernate. It decides whether to load a child class object while loading the parent class object. When we use association mapping...

3 minutes read.

Hibernate Annotation with 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 the specifications of the...

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 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-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 Many-to-One Mapping

Many-to-One Hibernate Mapping with Example A Many-to-One association mapping is the reverse of One-to-Many association mapping. For example, many (customers) are associated with one (vendor). In Hibernate, Many-to-One association mapping is applied from child class...

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 GeneratedValue Strategies

Hibernate GeneratedValue Strategies Hibernate supports some generation strategies to generate a primary key in the database table. We can access the strategy with the help of @GeneratedValue annotation. @GeneratedValue The @GeneratedValue annotation specifies how to...

3 minutes read.

Hibernate Named Query Using XML

A named query is a technique used to assemble all the queries (Native SQL and HQL) in a specific location and refer them by some name. It helps in reducing the mess...

3 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 Many-to-Many Mapping

Many-to-Many Hibernate Mapping with Example In Many-to-Many association mapping, more than one objects of a persistent class are associated with more than one objects of another persistent class. For example, many (categories) are related to...

3 minutes read.