2014-04-20 34 views
2

我必須同時需要更新的域類,我想使用事務以允許對兩者都進行更改或者兩者都不更改。例如:在一次保存兩個不同的域對象時使用Grails事務

我有兩個不同的領域類(用戶,並遵循)

User currentUser =.. 
User targetUser = .. 
Follow followUser = .. 

targetUser.follower = targetUser.follower + 1 
currentUser.follow = currentUser.follow + 1 
targetUser.save(flush:true) 
currentUser.save(flush:true) 
followUser.save(flush:true) 

我想這一切都一起發生或者如果一個失敗,這一切沒有發生,被回滾。我如何在Grails中做到這一點?我看到了DomainObject.withTransaction,但我有兩個不同的域,所以我應該嵌套?

回答

3

正確的解決方案是將此事務代碼移入服務。 documentation概述瞭如何創建和使用控制器中的服務。這是正確的解決方案。

但是,這不是唯一的方法。正如您所看到的,有能力使用withTransaction在事務範圍內運行代碼。例如(直接從documentation):

Account.withTransaction { status -> 
    def source = Account.get(params.from) 
    def dest = Account.get(params.to) 

    int amount = params.amount.toInteger() 
    if (source.active) { 
     source.balance -= amount 

     if (dest.active) { 
      dest.amount += amount 
     } 
     else { 
      status.setRollbackOnly() 
     } 
    } 
} 

的withTransaction閉合中的代碼可以跨越任何數量的域類。你可以混合搭配,只要你認爲合適。

再次強調。 正確的方法是使用服務

相關問題