gpt4 book ai didi

hibernate - 如何使用 JPA 和 Hibernate 修复 StaleObjectStateException

转载 作者:行者123 更新时间:2023-12-02 19:16:11 25 4
gpt4 key购买 nike

Controller 逻辑:

def updateObject() {

Object o = Object.get(params.id as Long)

o.otherObjects.clear()

objectDataService.saveObject(o.id)

OtherObject newObject = new OtherObject;

o.addToOtherObjects(newObject)

objectDataService.saveObject(o.id)

}

服务逻辑

def saveObject(long profileId) {
o.save(flush:true)
}

发生了什么

在 90% 的情况下,这会起作用。

问题

ERROR errors.GrailsExceptionResolver  - StaleObjectStateException occurred when processing request: [GET] /controller/updateObject - parameters:
stuff[]: data
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.path.Object#1].
Stacktrace follows:
Message: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.path.Object#1]

我已阅读相关问题并找到了您在上面看到的merge调用。它解决了大约 50% 的案例,但不是全部。

最佳答案

StaleObjectStateException:

As already commented out about this exception. When an invalid version-ed domain object is in the session during a flush (explicit or implicit) the version number is bumped but it is not persisted to the database. Then, when it becomes valid again and saved and flushed, hibernate considers it stale, since the version number does not match the version in the database and it throws a StaleObjectStateException.

这可以这样解决。

  1. you have to find out version value before doing the update , if it's 1 then you have to update by using program. at particular operation of update .
  2. By using @version annotation.

关于@版本:

The version number mechanism for optimistic locking is provided through a @Version annotation. Example: The @Version annotation

@Entity
public class Flight implements Serializable {
...
@Version
@Column(name="OPTLOCK")
public Integer getVersion() { ... }
}

这里,版本属性映射到 OPTLOCK 列,实体管理器使用它来检测冲突的更新,并防止丢失被最后提交获胜策略覆盖的更新 @version

有关 Grails 的更多详细信息,请参阅下面的链接,它有 Git hub 代码。
test for GRAILS-8937: HibernateOptimisticLockingFailureException

关于hibernate - 如何使用 JPA 和 Hibernate 修复 StaleObjectStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25531053/

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