【发布时间】:2011-05-04 06:53:36
【问题描述】:
我有一个代码可以保存一个 bean,并通过 Hibernate 更新数据库中的另一个 bean。它必须在同一个事务中进行,因为如果发生错误(f.ex 启动异常),必须为这两个操作执行回滚。
public class BeanDao extends ManagedSession {
public Integer save(Bean bean) {
Session session = null;
try {
session = createNewSessionAndTransaction();
Integer idValoracio = (Integer) session.save(bean); // SAVE
doOtherAction(bean); // UPDATE
commitTransaction(session);
return idBean;
} catch (RuntimeException re) {
log.error("get failed", re);
if (session != null) {
rollbackTransaction(session);
}
throw re;
}
}
private void doOtherAction(Bean bean) {
Integer idOtherBean = bean.getIdOtherBean();
OtherBeanDao otherBeanDao = new OtherBeanDao();
OtherBean otherBean = otherBeanDao.findById(idOtherBean);
.
. (doing operations)
.
otherBeanDao.attachDirty(otherBean)
}
}
问题是:
万一
session.save(bean)
启动错误,然后我得到 AssertionFailure,因为函数 doOtherAction(用于项目的其他部分)在抛出异常后使用 session。
我首先想到的是提取函数 doOtherAction 的代码,但后来我有相同的代码重复,这似乎不是最好的做法。
什么是重构它的最佳方法?
【问题讨论】:
标签: java hibernate transactions