What happens when you call SessionFactory.getCurrentSesion ()

advertisements

I user Session session=SessionFactory.getCurrentSssion() method in DAO as class level variable in my Struts2 application. I maintain Transaction in struts interceptor class. In may DAO class, when i try to get Data from DataBase sometime i am getting "session closed" exception. In my code for saveOrUpdate() method, i handle Hibernate Exception. In catch block i roll back the Transaction.

please help me, what happens when rollback the transaction if i use getCurrentSession() method.


You are using SessionFactory.getCurrentSession() of Hibernate which is used to create new session & it is managed by Hibernate automatically. It means when you call getCurrentSession(), Hibernate bind this session with local thread which will be accessed anywhere if you set hibernate.current_session_context_class property in your hibernate.cfg.xml file. This property bind your current session to a local thread.

Since, you are using getCurrentSession() method instead of openSession(), your session
will closed automatically by Hibernate as soon you perform any operation on database &
commit the transaction.

e.g.,

Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
Student student = new Student();
...
session.save(student);
transaction.commit();

To recover from this error, you should create session as & when needed using sessionFactory.openSession() method. By doing this you can have full control over session object.

e.g.,

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
    // do something
    transaction.commit();
} catch (Exception ex) {
    // on error, revert changes made on DB
    if (transaction != null) {
        transaction.rollback();
    }
} finally {
    session.close();
}

More Information :

  1. You can have a good idea Hibernate openSession() vs getCurrentSession()
  2. You can create managed session in Hibernate. Look at this ManagedSessionContext (Hibernate JavaDocs)

What happens when rollback the transaction ?

When you call rollback() method of Transaction it will revert all current changes done
on database. It doesn't have any concern with closing Hibernate session.