【问题标题】:StaleObjectStateException: Row was updated or deleted by another transaction?StaleObjectStateException:行已被另一个事务更新或删除?
【发布时间】:2013-09-07 00:27:37
【问题描述】:

我执行以下操作:

def currentUser = springSecurityService.currentUser
currentUser.name = "test"
currentUser.save(flush: true)

// some other code

currentUser.gender = "male"
currentUser.save(flush: true)        // Exception occurs

这是我得到的例外:

ERROR events.PatchedDefaultFlushEventListener  - Could not synchronize database state with session
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

如何防止出现此错误?最好的解决方案是什么?

我发现了不同的方法:

  1. here 可以使用 discard()
  2. here 你可以使用 merge()

我应该使用哪一个?

【问题讨论】:

    标签: spring hibernate grails grails-orm grails-2.0


    【解决方案1】:

    您应该使用合并 - 它会更新对象以匹配数据库中的当前状态。如果您使用丢弃它会将对象重置回数据库所拥有的,丢弃任何更改。 hibernate 会话中的其他所有内容都需要您自己管理。

    更重要的是代码应该写在一个服务中,这样就有一个数据库事务,你应该使用

    save(flush:true) 
    

    只在最后一次。

    def currentUser = springSecurityService.currentUser
    currentUser.name = "test"
    
    //    currentUser.save(flush: true) // removing this line because if a rollback occurs, then changes before this would be persisted.
    
    
    // some other code
    
    currentUser.gender = "male"
    currentUser.merge()                 // This will merge persistent object with current state
    currentUser.save(flush: true)
    

    【讨论】:

    • 你能按照你认为应该的方式重写我的代码吗?
    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多