我想将记录保存在两个数据库中
如果交易引发任何异常
两个数据库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();
        }
    }
}


其实在我上面的代码


首先,我正在进行辅助会话Transaction secondaryTx.commit();
然后我正在进行主会话事务primaryTx .commit();
万一我在主事务rollBack中遇到任何异常,
但是Secondary Transaction数据无法成功获取RevertedPrimary Transaction
如何还原两个交易数据?

最佳答案

    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();
        }
    }
}



提交前先刷新,它将抛出异常,因此您可以成功回滚。

10-04 19:50
查看更多