hibernate双向一对多插入重复项

发布于 2024-09-12 08:33:51 字数 1152 浏览 5 评论 0原文

我在这里遇到了亲子关系的问题。当我从收集端(子端)坚持时,我得到了 2 个新子项,而不是一个。

这是 hibernate 映射:

    <set name="children" inverse="true"
        cascade="all,delete-orphan" lazy="true"
        order-by="CHILD_ID desc">
        <key column="PARENT_ID" />
        <one-to-many class="com.mycompany.Child" />
    </set>
    <many-to-one name="parent" class="com.mycompany.Parent" not-null="true">
        <column name="PARENT_ID" />
    </many-to-one>

这是用于将子项添加到双向关系中的 java 代码:

// Persist logic...
Parent p = myParentService.findById(1);
Child c = new Child();
p.addChild(c);
myChildService.persist(child);

// Inside the parent class...
public void addChild(Child child)
{
    if (this.children == null)
        this.children = new LinkedHashSet<Child>();

    this.children.add(child);
    child.setParent(this);
}

如果我删除“this.children.add(child);”部分一切都按预期进行。这很令人困惑,因为 Hibernate 文档 这里说双向关系应该以这种方式工作。我缺少什么?

I'm having issues with a parent-child relationship here. When I persist from the collection side (child side) I get 2 new children instead of one.

Here is are the hibernate mappings:

    <set name="children" inverse="true"
        cascade="all,delete-orphan" lazy="true"
        order-by="CHILD_ID desc">
        <key column="PARENT_ID" />
        <one-to-many class="com.mycompany.Child" />
    </set>
    <many-to-one name="parent" class="com.mycompany.Parent" not-null="true">
        <column name="PARENT_ID" />
    </many-to-one>

Here is the java code used to add the child into the bidirectional relationship:

// Persist logic...
Parent p = myParentService.findById(1);
Child c = new Child();
p.addChild(c);
myChildService.persist(child);

// Inside the parent class...
public void addChild(Child child)
{
    if (this.children == null)
        this.children = new LinkedHashSet<Child>();

    this.children.add(child);
    child.setParent(this);
}

If I remove the "this.children.add(child);" part everything works as expected. This is confusing because the Hibernate documentaion here says that bidirectional relationships are supposed to work this way. What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怎言笑 2024-09-19 08:33:51

您在父级集合上打开了级联持久化,因此无需在子实体上显式调用持久化。如果父级处于托管状态,则新的子级将在下次事务提交/同步时保留。您链接的示例文档中未打开级联。

You turned on cascade persist on the parent's collection, so there is no need to call persist explicitly on the child entity. If the parent is in the managed state, the new child will be persisted the next time a transaction commits/there is a synchronization. Cascade is not turned on in the example documentation that you linked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文