我想将记录保存在两个数据库中
如果事务抛出任何异常
数据库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
已成功还原答案 0 :(得分:1)
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);
secondarySession.flush(); // add this line
primarySession.flush(); // add these line
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();
}
}
}