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

Example of First-Level Cache

Let’s understand the first-level cache using an example. There is an existing table (students) in the database containing some records.

  1. Create a POJO class

In this step, we are going to create a POJO class, i.e., Student .java. In this class, we are using two annotations, @Cacheable and @Cache.

  • @Cacheable- It specifies whether an entity should be cached if caching is enabled.
  • @Cache- It adds a cache strategy to root entity.  

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 nam
@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;
}
} 

The CacheConcurrencyStrategy specifies the type of strategy we are using.

  • 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

  
   
  • Create a class that retrieves the POJO object

It is a class which contains the main() methodused to run the application. 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=  sess.get(Student.class, 2);
sess.getTransaction().commit();
sess.close();
// open a new session
Session sess2= fact.openSession();
sess2.beginTransaction();
Student std1=  sess2.get(Student.class, 2);
sess2.getTransaction().commit();
sess2.close();
System.out.println("printed");
}
} 

OUTPUT