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


Related Topics

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

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

Hibernate Mapping Association- It means that two or more things are related to each other by some specific relation. In other words, it specifies how the objects are associated with each other. Hibernate mapping is one...

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

Hibernate Inheritance Joined Table

In this inheritance strategy, mapping of the child class fields is done with the common fields of the parent class in a separate table. In other words, the common entities between the child...

3 minutes read.

Hibernate Dialects

Hibernate Dialects Dialect is a Java class available in org.hibernate.dialect package, which helps to map Java Application with the database. To interact with the database, we need to define the required database dialect in...

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

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

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.

Hibernate vs. JPA

What is JPA? JPA stands for Java Persistence API, which defines a set of functionalities, standards, and concepts to the ORM tool. It is a framework used to manage relational databases. It is available...

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