2016-03-21 46 views
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(); 
     } 
    } 
} 
在我上面的代码

其实

  1. 首先我做二次会议事务secondaryTx.commit();
  2. 然后我做初级会话事务primaryTx .commit();
  3. 如果我在主要交易中遇到任何异常rollBack应该完成
  4. Secondary Transaction数据未得到RevertedPrimary Transaction成功回复
  5. 我怎样才能恢复交易双方的数据?
commit.It前

回答

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. 冲洗将抛出exception.So可以成功回滚。
+0

非常感谢,它工作正常。 –

相关问题