Note: This question is related for my previous one.
I am using hibernate.current_session_context_class=thread in my Hibernate configuration and getting Hibernate sessions via SessionFactory.getCurrentSession() as needed. So it does create or give me existing sessions when needed, so I do not take care of this.
This is all great, but what to do when I do get a HibernateException, a ConstraintViolationException for example? Then the current session I acquired before becomes invalid and I cannot use it anymore, not even for reading out some more data (according to many forums I’ve read). How can I discard and get then the new session within particular scope? I think calling SessionFactory.getCurrentSession() for the 2nd time still will return me the same invalid session!?
For the
ThreadLocalSessionContext, the session will be closed when the transaction finsihes. So in this case you should calltx.rollback(), thensessionFactory.getCurrentSession()to start afresh.