Hibernate :Clear Session ,Close Session

This part contains description of Hibernate session.clear() and session.close.

Hibernate :Clear Session ,Close Session

Hibernate :Clear Session ,Close Session

This part contains description of Hibernate session.clear() and session.close.

Hibernate Session.clear() :

void org.hibernate.Session.clear()

This method completely clear the session. It evicts all loaded objects and cancel all pending operations and clear caches for all objects.

Syntax : session.close()

Hibernate Session.close() :

Connection org.hibernate.Session.close() throws HibernateException

close() method is used when you are going to close your JDBC connection. This method ends your session by releasing the connection and cleaning up.
It is not mandatory to close the session but it is good to disconnect the connection

Syntax: session.close()

Example : In this example we are giving you main class code to show how to use clear() method and close() method.

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();
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);
query.executeUpdate();
System.out.println("New record inserted");
session.getTransaction().commit();
session.flush();
session.clear(); // Clearing the session object
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {

session.close(); // Closing the connection
}

}

}