Removing child from collection using JPA

倾然丶 夕夏残阳落幕 提交于 2020-01-12 02:58:07

问题


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;
  }
}

As you see Parent and Child 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 save

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?

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


回答1:


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 the cascade attribute), with a value of

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

Hibernate 3.5+ implement JPA 2.0



来源:https://stackoverflow.com/questions/3738934/removing-child-from-collection-using-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!