Home jpa removing child from collection
Reply: 0

jpa removing child from collection

user1262
1#
user1262 Published in June 20, 2018, 7:44 am

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 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.

Regards, Andrey

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.247468 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO