Share on Google+Share on Google+

Hibernate :Clear Session ,Close Session

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

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);
System.out.println("New record inserted");
session.clear(); // Clearing the session object
} catch (HibernateException e) {
} finally {

session.close(); // Closing the connection




Posted on: August 9, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Hibernate :Clear Session ,Close Session  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image