该异常通常是由于多个对象共享一个持久态集合而导致的。解决此问题的最简单方法是将集合定义为lazy-loading,以便在实际需要时才加载集合。同时,还可以将集合初始化为一个新的空集合对象,以确保每个对象都拥有自己的独立集合。
代码示例:
@Entity public class Parent {
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.EXTRA)
private Set children = new HashSet<>();
public void addChild(Child child) {
children.add(child);
child.setParent(this);
}
}
@Entity public class Child {
@ManyToOne(fetch = FetchType.LAZY)
private Parent parent;
public void setParent(Parent parent) {
this.parent = parent;
}
}