如何在同一个Hibernate Transaction中保存两个数据库记录?

时间:2016-03-21 05:36:31

标签: mysql database hibernate session transactions

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

实际上在上面的代码中

  1. 首先,我正在进行辅助会话事务secondaryTx.commit();
  2. 然后我正在进行主要会话事务primaryTx .commit();
  3. 如果我在主要交易rollBack中收到任何例外,则应该
  4. Secondary Transaction数据未获得RevertedPrimary Transaction已成功还原
  5. 如何还原交易数据?

1 个答案:

答案 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();
        }
    }
}
  1. 提交前刷新。它会抛出异常。所以你可以成功回滚。