2013-07-18 49 views
3

我可以在withTransaction關閉內提交嗎?我想要做這樣的事情我Quartz工作中:我可以在內部進行交易關閉嗎

Author.withTransaction { 
    def author = Author.get(1) 
    author.staus = 'processing' 
    author.save() 
    commit // how can i do this? 
    // so some work here which takes 1-2 minutes 
    author.status = 'completed' 
    author.save() 
} 

的想法是,我想有一個狀態屏幕,該屏幕將顯示其正在此刻處理所有Author S,所以我想設置狀態爲processing,並能夠從控制器看到此狀態。

編輯: 這將工作沒有withTransaction,但我必須有withTransaction那裏......見this question

+0

提交將在每個事務結束時發生。 – Alidad

+1

我知道。我問有沒有辦法在'withTransaction'內執行提交? – zoran119

+0

作業將按照「作者」或批處理執行? – dmahapatro

回答

2

爲了讀取來自不同未提交事務的值,必須將數據庫隔離級別設置爲「未提交讀取」,這通常是您可能做錯某事的指標。

是否有任何理由不能將其分爲單獨的交易?一個是將記錄標記爲「正在進行中」,另一個是執行實際工作?

Author.withTransaction { 
    def author = Author.get(id) 
    author.status = 'processing' 
    author.save() 
} 

Author.withTransaction() { 
    def author = Author.get(id) 
    // do some work 
    author.status = 'completed' 
    author.save() 
} 
+0

好的。我在這裏只有一個問題,如果第二個事務中的任務發生了問題,第一個事務如何回滾? – dmahapatro

+1

幾種方法。我會將其包裝在服務方法中並使用嵌套事務。但是如果你想堅持使用程序化的tx管理,你可以在第二個事務中自己捕獲異常,可以使用'TransactionStatus'參數來引起回滾,並有邏輯在事實之後回滾第一個異常。 – codelark

+1

快速編輯 - 「回退第一個」並不完全正確,因爲您實際上只是執行另一個更新來清除狀態。 – codelark

0

我會盡量堅持@ codelark的方法,儘可能地用編程方式處理事務併爲回滾添加邏輯。

這是一個同時發生的事情,我也在這個問題上與密碼員一起挖地面。以下是我現在有:

Author.withSession{session-> 
     def author = Author.get(blahId) 
     try{ 
      def tx = session.beginTransaction() 
      //Update status to processing 
      author.status = 'processing' 
      tx.commit() 

      //Do your 1 - 3 minutes task 
     } catch(e){ 
      //If there is any exception in that task then rollback transaction 
      tx?.setRollbackOnly() 
     } 

     if(!tx.isRollbackOnly()){ 
      try { 
       def tx2 = session.beginTransaction() 
       //Update author status to completed 
       //Few pain points can also be taken care of here, like checking if the task completed as expected etc.. 
       author.status = 'completed' 
       tx2.commit() 
      } 
      catch(Exception e) { 
       tx2?.setRollbackOnly() //If you want 
      } 
     } 
    } 

@Alidad是說承諾絕對正確/沖洗發生在withTransaction塊的結尾。所以flush: true裏面withTransaction將無法​​正常工作。

相關問題