Hibernate: Session Caching

In this section we will discuss first type of caching in Hibernate that is Session caching.

Hibernate: Session Caching

Hibernate: Session Caching

In this section we will discuss first type of caching in Hibernate that is Session caching.

Session Caching :

First type cache is called Session Cache. It is necessary cache as all the requests pass trough it. In hibernate by default ,it is automatically enabled.
For session cache ,there is no need of any setting. It is by default enabled and you cant disable it. Session cache is associated with your session object and it is limited for one session only.
It is loaded at the time you open session and its scop till the session exist. If you load the same object by opening other session then again the object will load database and cache is maintained for the new session.

Example : Here is simple example to display record of student whose roll number is 5.By default, Session cache  is enabled .

package net.roseindia.main;

import net.roseindia.table.Student;
import net.roseindia.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;

public class HibernateSessionCache {
public static void main(String args[]) {
Session session = HibernateUtil.getSessionFactory().openSession();
int roll = 5;
try {
Student student = (Student) session.load(Student.class, roll);
// Loading student record of roll=5)

System.out.println("RollNo. :" + student.getRoll());
System.out.println("Name :" + student.getName());
System.out.println("Course :" + student.getCourse());
session.close();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}

Output :

Hibernate: select student0_.roll_no as roll1_0_0_, student0_.course as course0_0_, student0_.name as name0_0_ from student student0_ where student0_.roll_no=?
RollNo. :5
Name :Johny
Course :C