【发布时间】:2013-09-26 01:17:15
【问题描述】:
目前在具有本地和远程 EJB、MDB(单例和无状态)的 JavaEE 应用程序服务器中,我正在为 Hibernate Core 使用 JDBC-Transactions。
管理自己的所有打开和关闭,提交休眠会话和事务可能会导致连接泄漏和未提交的事务。
特别是在编程错误导致自定义或未经检查的异常未被捕获并抛出给远程客户端的情况下。
在发生错误时确保关闭休眠会话并回滚事务的最简单或最佳方法是什么?
使用容器管理事务 (CMT) 还是可以在任何 EJB 方法返回时调用的拦截器中关闭会话?
一种简单的方法是将会话范围的用法包装在 try-catch 块中并捕获任何类型的异常,但更倾向于使用更少代码的通用方法。
编辑:远程 EJB 示例
-
我的低级 Hibernate DAO 确实会关闭连接并在抛出异常时回滚事务。如果连接仍然打开,问题是 DAO 访问之间的业务逻辑。*
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); }
现在我正在使用一个大的 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);
}
}
【问题讨论】: