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

标签 spring hibernate grails gorm grails-2.0

我执行以下操作:

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/

    相关文章:

    java - 可以使用 Spring JPA 设置 'set nocount on'

    java - Spring 请求将 URL 映射到一个 Controller

    hibernate - 为什么Hibernate在启动时要花费数小时的负载?

    java - 如何从非主键表的 hibernate 列表中选择数据,其中所有列的where子句数据都相同

    java - 当我需要在命令类之外的表单上显示数据时,如何使用 SimpleFormController?

    java - 从具有 OutputStream 的 Spring @Controller 返回文件

    spring - 在 Quartz 作业中使用 PersistenceContext

    file - 如何设置 grails 环境变量?

    java - Rundeck: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 必须首先发出 STARTTLS 命令

    java - 在 jetty 服务器中启动Grails