gpt4 book ai didi

spring - StaleObjectStateException : Row was updated or deleted by another transaction?

转载 作者:行者123 更新时间:2023-12-04 03:52:13 25 4
gpt4 key购买 nike

我执行以下操作:

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

// some other code

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

这是我得到的异常(exception):
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)

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

我发现了不同的方法:
  • here可以使用discard()
  • here可以使用merge()

  • 我应该使用哪一个?

    最佳答案

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

    更重要的是,应将代码编写到服务中,以便进行数据库事务,并且应使用

    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)

    关于spring - StaleObjectStateException : Row was updated or deleted by another transaction?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18597892/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com