9 grails spring hibernate grails-orm 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
Run Code Online (Sandbox Code Playgroud)
这是我得到的例外:
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)
Run Code Online (Sandbox Code Playgroud)
我该如何防止此错误?什么是最好的解决方案?
我找到了不同的方法:
我应该使用哪一个?
Anu*_*eja 10
您应该使用merge - 它将更新对象以匹配数据库中的当前状态.如果使用discard,它会将对象重置为数据库所具有的内容,并放弃所有更改.您需要自行管理的休眠会话中的其他所有内容.
更重要的是,应该在服务中编写代码,以便存在数据库事务,您应该使用
save(flush:true)
Run Code Online (Sandbox Code Playgroud)
一次只在最后.
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)
Run Code Online (Sandbox Code Playgroud)