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 :
- You can have a good idea Hibernate openSession() vs getCurrentSession()
- 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.