What happens when you call SessionFactory.getCurrentSesion ()

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()

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.


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

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.


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

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.
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » What happens when you call SessionFactory.getCurrentSesion ()

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录