我执行以下操作:
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)
如何防止此错误?最佳解决方案是什么?
我找到了不同的方法:
答案 0 :(得分:10)
您应该使用merge - 它将更新对象以匹配数据库中的当前状态。如果使用discard,它会将对象重置为数据库所具有的内容,并放弃所有更改。您需要自行管理的休眠会话中的其他所有内容。
更重要的是,应该在服务中编写代码以便存在数据库事务,并且应该使用
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)