hibernate双向一对多插入重复项
我在这里遇到了亲子关系的问题。当我从收集端(子端)坚持时,我得到了 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在父级集合上打开了级联持久化,因此无需在子实体上显式调用持久化。如果父级处于托管状态,则新的子级将在下次事务提交/同步时保留。您链接的示例文档中未打开级联。
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.