IMParasharG
IMParasharG

Reputation: 1895

JPA: Delete children in OneToMany

I have a OneToMany mapping as below

Parent:

@OneToMany(mappedBy = parent, orphanRemoval = true, cascade = { CascadeType.ALL})
private List<Child> childs = new ArrayList<Child>();

Child:

@ManyToOne
@JoinColumn(name = "parentid")
private Parent parent;

While updating the Parent entity, I am getting an exception:

A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance

My code:

parent.getChild().clear();
parent.setChild(childList)

Upvotes: 1

Views: 1228

Answers (1)

kostja
kostja

Reputation: 61538

You remove the children from the parent, but as Child is the owning side, you have to remove the reference to the Parent from the Child entities.

for (Child child: children) {
   child.setParent(null);
}

Upvotes: 1

Related Questions