gpt4 book ai didi

hibernate - 交叉依赖问题:对象引用未保存的 transient 实例,在刷新之前保存 transient 实例

转载 作者:行者123 更新时间:2023-12-02 14:50:32 27 4
gpt4 key购买 nike

似乎一遍又一遍地问这个问题,我仍然找不到解决我问题的答案。我在下面有一个域模型。每个新创建或更新的“安全用户”都需要我确保其具有配置文件,如果没有,则创建一个新的配置文件并分配给它。

配置文件的要求相同-在保存期间每次检查它是否具有工作空间,如果没有,则创建一个工作空间。这样做是为了确保所有“高级用户”都有至少一个工作区。除了所有者本人之外,工作空间可能具有不同的贡献者。

当我尝试保存“秒用户”时,总是会得到:

object references an unsaved transient instance save the transient instance before flushing

总的来说,我确实了解问题的性质。在构造函数中传递的实例不会持久保存,因此没有ID。我仍然不知道如何强制这3个插入成为单个事务的一部分并正确处理引用。
class SecUser implements Serializable {

String email

static hasOne = [profile: Profile]

def beforeValidate() {
if (profile == null) {
profile = new Profile(secUser: this)
}
profile.validate()
}

}

class Profile {

static belongsTo = [secUser: SecUser]

static hasMany = [workspaces: Workspace]

static constraints = {
workspaces minSize: 1
}

def beforeValidate() {
if (workspaces == null || workspaces.isEmpty()) {
def workspace = new Workspace(owner: this).save()
workspaces = [workspace]
}
}
}

class Workspace {

String title = "Workspace ${10000 + new Random().nextInt(89999)}"

static hasOne = [owner: Profile]

static belongsTo = Profile

static hasMany = [contributors: Profile]

}

更新1

我已更换
workspaces = [workspace]


this.addToWorkspaces(workspace)

现在我得到这个:

ERROR spi.SqlExceptionHelper - Referential integrity constraint violation: "FK_MYFCABJIQ83AG2CLBDF61MPA5: PUBLIC.PROFILE_WORKSPACES FOREIGN KEY(WORKSPACE_ID) REFERENCES PUBLIC.WORKSPACE(ID) (0)"; SQL statement: insert into profile_workspaces (profile_id, owner_id) values (?, ?) [23506-176].



生成了一个新的联接表,该表具有3列。我看到它试图做出错误的插入。它应该插入owner_id,workspace_id(profile_id应该为空)

最佳答案

当我处理涉及多个域对象的业务交易时,我创建了Grails服务。使用服务将简化域单元测试,并且还有助于描述您的代码试图完成的工作。可以将其视为事务脚本设计模式(四人制)。

您的服务可以具有create()和update()方法,然后可以从 Controller 中调用这些方法。然后,您的服务将根据需要连接SecUser,Profile和Workspace。

关于hibernate - 交叉依赖问题:对象引用未保存的 transient 实例,在刷新之前保存 transient 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31980056/

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