Hibernate Session

This section contains the explanation of hibernate session.

Hibernate Session

Hibernate Session

This section contains the explanation of  hibernate session.

Hibernate Session management:

Session interface is defined in org.hibernate.Session.It plays very important role in databases connection.
It is constructed by Hibernate to get a connection with a database. It is light weight and run for a short time. You can open session and perform operations as create, read and delete until the session is closed. Hibernate loads database object ,which is associated with the session. You can save and retrieve persistent object through a session object.

Example :

Here is an example showing how to open and close session.

package net.roseindia.main;

import net.roseindia.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class MainClazz {

public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession(); //session is opened
Transaction transaction = null;
try {

transaction = session.beginTransaction();
String sql = "insert into student(roll_no, name,course) values(12, 'Roxi' ,'Hibernate')";
Query query = session.createSQLQuery(sql); //using session for createSQLQuery
query.executeUpdate();
System.out.println("New record inserted");
session.getTransaction().commit();
session.flush();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close(); //session close
}
}
}