使用JPA从集合中删除孩子 [英] Removing child from collection using JPA

查看:78
本文介绍了使用JPA从集合中删除孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Web应用程序中通过Hibernate使用JPA.这是两个实体(仅显示吸气剂):

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<Child> children;

  @OneToMany(fetch=FetchType.EAGER, mappedBy="parent", cascade={CascadeType.ALL})
  public Collection<Child> getChildren() {
    return children;
  }
}

如您所见,ParentChild表示一对多".

As you see Parent and Child relate as "one-to-many".

现在,我需要加载一个Parent实例,删除部分或全部子代并保存更改.以下是对我不起作用的代码:

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 save

在上面的示例中未删除子实体.现在,我必须为每个孩子手动调用entityManager.remove().

Child 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?

请注意,我不想使用特定于Hibernate的功能,只能使用纯JPA.

Please notice that I don't want to use Hibernate-specific functionality, only pure JPA.

推荐答案

对于JPA 2.0,您可以设置

For JPA 2.0 you can set orphanRemoval=true of the @OneToMany

对于JPA 1.0,您应该使用特定于休眠的注释.这是@Cascade注释(而不是cascade属性),其值为

For JPA 1.0, you should use hibernate-specific annotations. That is the @Cascade annotation (instead of the cascade attribute), with a value of

@Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN})

Hibernate 3.5+实现JPA 2.0

Hibernate 3.5+ implement JPA 2.0

这篇关于使用JPA从集合中删除孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆