2016-03-21 3 views
0

レコードを2つのデータベースに保存する トランザクションによって例外がスローされた場合 データベースTransactionrevertedになる 私のコードにどのように実装できますか?ここで 同じHibernate Transactionで2つのデータベースレコードを保存する方法は?

は、その後、私はプライマリセッショントランザクションをやってる

  1. まず私はセカンダリセッショントランザクションsecondaryTx.commit();
  2. をやってる私のサンプルコード

    私の上記のコードでは実際に
    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(); 
         } 
        } 
    } 
    

    あるprimaryTx .commit();

  3. プライマリ取引で例外が発生した場合rollBack
  4. しかしSecondary TransactionデータReverted取得し、Primary Transactionが正常に私は両方のトランザクションデータを戻すことができますどのように
  5. を差し戻していませんか?

答えて

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 commit.It前にフラッシュがスローされます。
+0

ありがとうございます。うまくいきました。 –

関連する問題