Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JPA: How to delete children in a OneToMany relationship?

843830Aug 14 2008 — edited Sep 10 2008
Bear with me, since I'm a JPA newbie :-)

I have a simple one to many relationship where the parent has an ID and the children have the same as foreign key.

Now I'd like to replace all children, which (probably) means I have to delete all the existing children first and then merge the parent. Note that I can't just delete the parent and re-insert it, since it has relations to other tables.

So... all I need to do first is to delete all children. I load the parent and then
      for ( Iterator<Child> iterator = parent.getChildren().iterator(); iterator.hasNext(); )
      {
        Child child = iterator.next();
        child.setParent( null );
        iterator.remove();
      }
      entityManager.merge( parent );
In that case I get
javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: ...Child.parent
If I don't set the parent to null, then the children are not deleted.

I tried using a query to delete the children, however I don't have the foreign key column mapped directly, since I have the parent mapped in the child as
  @ManyToOne( optional = true )
  @JoinColumn( name = "parent_id", nullable = false )
  private Parent parent;
This seems such a trivial problem, but searching around the Internet and looking it up in books didn't show me any usable solution...

Thanks for your help!
Eric

Btw, I'm using Hibernate in JBoss 5
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 8 2008
Added on Aug 14 2008
12 comments
17,386 views