2013-09-05 72 views
2

我有一些代碼從表中讀取要發送併發送的郵件列表。自動調用和數據庫回滾

的順序操作如下:

  1. 設置標誌作爲發送表中
  2. 進行自動呼叫
  3. 提交

的原因之前,具有更新自動呼叫是,如果某些事情失敗了,我可以回滾而不進行自動呼叫。但如果是相反的話,我最終會在可能的情況下撥打電話而無法更新記錄(如果db出現問題)。

public class MyDao { 

    public void doSomethingOnDb() { 
     try { 
      // operation 1 : execute an update (setting the letter as sent) 
      // operation 2 : make automatic call  
      // operation 3 : commit 
     } 
     catch(Exception e) { 
      // Rollback 
     } 
    } 
} 

我不喜歡這裏要說的是,我把一個功能,使道內自動呼叫,這是不是什麼DAO預期的事情。但是如果我將邏輯分開,我不能確定表格中的國旗是否真實。我們可以撥打電話,無法將標誌更新到db:

public class MyDao { 

    public void doSomethingOnDb() { 
     try { 
      // operation 1 : execute an update (setting the letter as sent) 
      // operation 2 : commit 
     } 
     catch(Exception e) { 
      // Rollback 
     } 

    } 
} 

public void someOtherMethodSomewhere() { 
    try { 
     new MyDao().doSomethingOnDb(); 
     // operation 3 : make the automatic call 
    } 
    catch(Exception e) { 
    } 
} 

那麼,你會如何做到這一點?還有其他解決方案嗎?

回答

0

這是一個經典的多資源交易(分佈式交易)。我可以推薦您閱讀關於XA交易的信息,例如Two Phase Commit protocol

也許你正試圖解決另一個問題?如果我理解正確,那麼也許你只需要改變你的代碼?例如。您可以從dao返回成功:

if(doSomethingOnDb()) 
{ 
    //make the automatic call 
} 

即,如果更改成功完成並提交,則dao調用返回true。

你也可以只遙,從doSomethingOnDb異常,如果它失敗了,在這種情況下

try { 
    new MyDao().doSomethingOnDb(); 
    // operation 3 : make the automatic call 
} 
catch(Exception e) { 
} 

跳過operation 3並落入catch塊。

或者只是傳遞給DAO來執行一個功能:

public void doSomethingOnDb(Runnable precommit) { 
    try { 
     // operation 1 : execute an update (setting the letter as sent) 
     precommit.run();  
     // operation 3 : commit 
    } 
    catch(Exception e) { 
     // Rollback 
    } 
} 

... 
myDao.doSomethingOnDb(new Runnable() 
{ 
    void run() 
    { 
     // operation 3 : make the automatic call 
    } 
}); 
0

不能只需將DAO操作分成子方法?例如:

public class MyDao { 
    public void executeAnUpdate() {...} 
    public void commit() {...} 
} 

public class MyBusiness { 
    public void run() { 
     myDao.executeAnUpdate(); 
     // make the automatic call 
     myDao.commit(); 
    } 
} 
+0

好的,也許創建一個回滾方法然後。但是這樣就不那麼鬆散了 – user1883212