【发布时间】:2016-07-07 12:53:53
【问题描述】:
我想将记录保存在两个数据库中
如果事务抛出任何异常
两个数据库Transaction 都应该得到reverted
如何在我的代码中实现?
这是我的示例代码
public void save(Vendor vendor, Ledger ledger) throws Exception
{
Transaction primaryTx = null, secondaryTx = null;
Session primarySession = null, secondarySession = null;
try
{
secondarySession = HibernateUtil.getSession("secondarydb");
secondaryTx = secondarySession.beginTransaction();
secondarySession.save(ledger);
vendor.setLedgerId(ledger.getId());
primarySession = HibernateUtil.getSession("primarydb");
primaryTx = primarySession.beginTransaction();
primarySession.saveOrUpdate(vendor);
secondaryTx.commit();
primaryTx.commit();
}
catch (Exception e)
{
if (secondaryTx != null)
{
secondaryTx.rollback();
}
if (primaryTx != null)
{
primaryTx.rollback();
}
throw e;
}
finally
{
if (secondarySession != null && secondarySession.isOpen())
{
secondarySession.close();
}
if (primarySession != null && primarySession.isOpen())
{
primarySession.close();
}
}
}
其实在我上面的代码中
- 首先我正在做辅助会话事务
secondaryTx.commit(); - 然后我在做主会话事务
primaryTx .commit(); - 如果我在主事务
rollBack中遇到任何异常,应该完成 - 但是
Secondary Transaction数据没有得到Reverted和Primary Transaction成功还原 - 如何恢复两个交易数据?
【问题讨论】:
标签: mysql database hibernate session transactions