Hibernate Session Management

In this section we will discuss How to manage Hibernate session.

Hibernate Session Management

Hibernate Session Management

In this section we will discuss How to manage Hibernate session.

Hibernate Session :

A session is used for getting connection to the database. When you begin persisting or loading objects to/from the database, a session object is instantiated.
It is light weighted and designed to be instantiated each time whenever interaction is needed with the database.
When a session object is instantiated, a connection is made to the database, thus the interactions should be fairly quick to ensure the application doesn't keep database connection open needlessly. At the time you create session it open single database and holds it until session is closed.

For Session import interface org.hibernate.Session.It is main runtime interface between your java application and Hibernate.
Lifecycle of a Session runs under the beginning and end of your logical transaction.
The main function of the Session is create ,rad and delete operations for instances of mapped entity class.

Session instances lives in one of three states -

  • transient: never persistent, not associated with any Session
  • persistent: associated with a unique Session
  • detached: previously persistent, not associated with any Session

Here we are showing syntax of session -

Session session = HibernateUtil.getSessionFactory().openSession(); //opening Session

....
....

session.save(student); //saving student object through session

....
....

session.close(); //Closing session.Now it does not exist.

Example : Here we are giving you main class code to show how Session plays an important role in our application. In this example we are saving student record.

package net.roseindia.main;

import net.roseindia.table.Student;
import net.roseindia.util.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class MainClazz {

public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Student student = new Student();
student.setName("Glinto");
student.setCourse("Hibernate");
session.save(student);
transaction.commit();
System.out.println("Record saved");
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}

Output:

Hibernate: insert into student (course, name) values (?, ?)
Record saved