"Clearly, whenever an exception happens, the database transaction has to be rolled back. Another rule in Hibernate is that the current Session has to be closed and discarded immediately, it can't be re-used. Hence, this is all you have to do to handle exceptions from a Hibernate perspective. Of course you might want to retry some unit of work if it failed, or you might want to display custom errors. All of this is outside of the scope of Hibernate and can be implemented in any way you like."
-
How Do I Handle Exceptions in Hibernate and JPA Web Applications? So, you're doing a web application, and you're running into a closed session. So, we can assume the session was open at one point, and somewhere along the line, it got closed.
Why did the session get closed? When a session gets closed, that might indicate a full
unit of work is completed, and as such, you will need to open a new session. But was the session closed due to a HibernateException?
Since most web applications have very short request-response cycles, often a problem with the Hibernate Session can be seen as unrecoverable, at least for that particular request and response cycle. It's often sufficient to send a message back to the user to say the operation failed, and ask them to resubmit their form. Or, if there is something in particular that was on the form that triggered the error, you can ask them to make a change.
If you are closing the session yourself, and it's not an error, you might want to think about extending the life of the session. A very, very common
pattern is to open a Hibernate Session transaction as soon as a request comes in. Then, when all the processing is done, from the
Servlet to the final
JSP, the transaction is closed. This can be achieved by opening and closing the Hibernate Session in a ServletFilter. And this doesn't tie you to Servlets and JSPs, as you can wrap a filter around a
struts action or a
JSF bean.
You can read more about this by digging through documentation on the "Open Session in View" design practice. Here's a few links from Hibernate.org that might help out a bit. The link about Transactions is very detailed and interesting.
Open Session in View Hibernate/Transaction Design Pattern/Practice Hibernate Transactions and Custom Filter Interceptors Post back and let's figure this thing out!
-Cameron McKenzie
[ May 12, 2008: Message edited by: Cameron Wallace McKenzie ]