Java 使用 JPA 从集合中删除子项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3738934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing child from collection using JPA
提问by Andrey
I'm using JPA over Hibernate in my web-app. Here are two entities (only getters are shown):
我在我的网络应用程序中通过 Hibernate 使用 JPA。这里有两个实体(只显示了 getter):
class Child {
private Parent parent;
@ManyToOne(optional=false)
@JoinColumn(name="parent_id", referencedColumnName="parent_id", nullable=false, updatable=false)
public Parent getParent() {
return parent;
}
}
class Parent {
private Collection<Child> children;
@OneToMany(fetch=FetchType.EAGER, mappedBy="parent", cascade={CascadeType.ALL})
public Collection<Child> getChildren() {
return children;
}
}
As you see Parent
and Child
relate as "one-to-many".
如您所见,Parent
并将其Child
关联为“一对多”。
Now I need to load a Parent
instance, remove some or all children and save the changes. Below is code which does not work for me:
现在我需要加载一个Parent
实例,删除部分或全部子项并保存更改。以下是对我不起作用的代码:
Parent p = entityManager.find(Parent.class, 12345L); // load entity
p.getChildren().clear(); // remove all children
entityManager.merge(p); // try to save
Child entities are not remove in the example above. Now I have to manually call entityManager.remove()
for each child.
在上面的示例中没有删除子实体。现在我必须手动entityManager.remove()
为每个孩子打电话。
Is there any easier way to manage child collection?
有没有更简单的方法来管理子集合?
Please notice that I don't want to use Hibernate-specific functionality, only pure JPA.
请注意,我不想使用 Hibernate 特定的功能,只想使用纯 JPA。
采纳答案by Bozho
For JPA 2.0 you can set orphanRemoval=true
of the @OneToMany
对于JPA 2.0你可以设置 orphanRemoval=true
的@OneToMany
For JPA 1.0, you should use hibernate-specific annotations. That is the @Cascade
annotation (instead of the cascade
attribute), with a value of
对于 JPA 1.0,您应该使用特定于休眠的注释。那是@Cascade
注释(而不是cascade
属性),其值为
@Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN})
Hibernate 3.5+ implement JPA 2.0
Hibernate 3.5+ 实现 JPA 2.0