/**父对象*/
class Parent {
@OneToMany(mappedBy = "parent")
List<Child> children;
}
/**子对象*/
class Child{
Parent parent;
}
在如上所列的OneToMany关系中,如果想要清空某个Parent对象的所有子对象,以下的代码会失败:
Parent parent = parentRepository.findById(id);
parent.setChildren(Collectons.emptyList());
parentRepository.save(parent) //这里会报错A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance
原因是Collections.emptyList()得到的是一个不受管的List。正确的做法是:
parent.getChildren().clear(); //getChildren()返回了一个受管的List
parentRepository.save(parent);