0
我想在两个数据库中保存记录 万一事务抛出异常 两个数据库Transaction
都应该得到reverted
我该如何在我的代码中实现?如何在同一个Hibernate事务中保存两个数据库记录?
这里是我的示例代码
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
成功回复 - 我怎样才能恢复交易双方的数据?
非常感谢,它工作正常。 –