jpa将孩子从收藏中删除 [英] jpa removing child from collection
问题描述
我在Web应用程序中使用JPA而不是Hibernate。以下是两个实体(仅显示获取者):
class子元素{
私有父母;
@ManyToOne(可选= false)
@JoinColumn(name =parent_id,referencedColumnName =parent_id,nullable = false,updatable = false)
public Parent getParent ){
返回父母;
}
}
类父母{
私人收藏儿童;
@OneToMany(fetch = FetchType.EAGER,mappedBy =parent,cascade = {CascadeType.ALL})
public Collection getChildren(){
return children;
当你看到
Parent
和Child
相关为一对多。
现在我需要加载一个
父母
实例,删除部分或全部孩子并保存更改。下面是不适合我的代码:
父p = entityManager.find(Parent.class,12345L); // load entity
p.getChildren()。clear(); //删除所有的孩子
entityManager.merge(p); //试图保存
在上面的例子中,子实体不会被删除。现在我必须为每个孩子手动调用
entityManager.remove()
。有没有更简单的方法来管理儿童收藏?请注意,我不想使用Hibernate特有的功能,只使用纯JPA。
问候,
Andrey
<对于JPA 2.0,您可以设置解决方案
@OneToMany
的#orphanRemoval%28%29rel =noreferrer>orphanRemoval = true
对于JPA 1.0,您应该使用hibernate特定的注释。这是
@Cascade
注释(而不是cascade
属性),值为@Cascade({CascadeType.ALL,CascadeType.DELETE_ORPHAN})
Hibernate 3.5+实现JPA 2.0
I'm using JPA over Hibernate in my web-app. Here are two entities (only getters are shown):
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 children; @OneToMany(fetch=FetchType.EAGER, mappedBy="parent", cascade={CascadeType.ALL}) public Collection getChildren() { return children; } }As you see
Parent
andChild
relate as "one-to-many".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 p = entityManager.find(Parent.class, 12345L); // load entity p.getChildren().clear(); // remove all children entityManager.merge(p); // try to saveChild entities are not remove in the example above. Now I have to manually call
entityManager.remove()
for each child.Is there any easier way to manage child collection? Please notice that I don't want to use Hibernate-specific functionality, only pure JPA.
Regards, Andrey
解决方案For JPA 2.0 you can set
orphanRemoval=true
of the@OneToMany
For JPA 1.0, you should use hibernate-specific annotations. That is the
@Cascade
annotation (instead of thecascade
attribute), with a value of@Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN})
Hibernate 3.5+ implement JPA 2.0
这篇关于jpa将孩子从收藏中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!