簡體   English   中英

一次保存兩個不同的域對象時使用Grails Transaction

[英]Using Grails Transaction when saving two different domain object in one shot

我必須要同時更新需要更新的域類,我想使用事務以便允許對兩者或兩者都不進行更改。 例如 :

我有兩個不同的域類(用戶和關注)

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) 

我希望所有這些都一起發生,或者如果一個失敗,則所有事情都不會發生並被回滾。 我怎樣才能做到這一點? 我看到了DomainObject.withTransaction,但是我有兩個不同的域,所以我應該嵌套嗎?

正確的解決方案是將該事務代碼移至服務中。 文檔概述了如何從控制器創建和使用服務。 那是正確的解決方案。

但是,這不是唯一的方法。 如您所見,可以使用withTransaction在事務范圍內運行代碼。 例如(直接來自文檔 ):

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閉包內的代碼可以跨越任意數量的Domain類。 您可以根據自己的喜好混合搭配。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM