Currently in my JavaEE application-server with local and remote EJB's, MDB's (Singleton and Stateless) I am using JDBC-Transactions for Hibernate Core.
Managing myself all my opening and closing, committing of hibernate sessions and transactions can lead to connection-leaks and uncomitted transactions.
Especially in the case of programming errors resulting in custom or unchecked exceptions that are not catched and thrown to the remote client.
What is the easiest or best way to make sure my hibernate sessions are closed and transactions rolled back in case an error is thrown?
Use container-managed transactions (CMT) or is it possible to close sessions within an interceptor that is called on return of any EJB methods?
One easy way would be to wrap the session-scoped usage in a try-catch block and catching any type of Exception, but a general approach with less code would be favored.
Edit: Remote EJB Example
My low-level Hibernate DAO does closes connection and rolls back transaction on thrown exceptions. Problematic is business-logic between DAO accesses in case connection is still open.*
public void doSomething(Foo foo) throws Exception { // open session and transaction Session session = DAO.openSession(); // retrieve data Bar bar = DAO.get(session, ...) // call other methods which throws an exception resulting in open connection doOtherStuff(foo, bar) DAO.save(session, foo); // commit transaction DAO.closeAndCommitSession(session); }
Right now i am using a big try-catch-finally:
public void doSomething(Foo foo) throws Exception
{
// open session and transaction
Session session = DAO.openSession();
try
{
// retrieve data
Bar bar = DAO.get(session, ...)
// call other methods which throws an exception resulting in open connection
doOtherStuff(foo, bar)
DAO.save(session, foo);
}
catch (final Exception e)
{
DAO.rollBackTransaction(session);
throw e;
}
finally
{
DAO.closeAndCommitSession(session);
}
}