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

Posted on Posted in Hibernate

Hibernate Class:

@Entity
@Table(name="Person")
public class Person{
    @OneToMany(mappedBy = "children", cascade = CascadeType.ALL, 
       orphanRemoval = true)
     private Set<Child> children;
... //setters and getters
}

 

Error occurs when in controller you are trying to set it to null instead of clearing the set/list, the following pseudo code will throw an exception as “A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance”

public String deleteChildren(HttpServletRequest request, 
   @ModelAttribute("person") Person person, BindingResult result, Model model) {
     person.setChildren(null);
     repository.save(person); 
}

instead use:

person.getChildren.clear();
repository.save(person);

Leave a Reply