更新时间:2023-01-14 16:19:01
在 manyToMany 中级联删除它不仅适用于链接表,还适用于关联的另一侧.
Cascade Remove in a manyToMany it's not only applied to the link table, but to the other side of the association as well.
因此,继承 remove 的 Cascade.ALL 在多对多上几乎总是一件坏事,因为它最终不仅会从关联表中删除内容.
So Cascade.ALL which inherit remove too is almost always a bad thing to have on a manyToMany as it ends up deleting things not only from association table.
您想要的是在实体中添加和删除方法来完成工作并保持两个列表同步:
What you want is to have add and remove method in your entities to do the work and keep both list synchronized:
public class ClassA extends [...] implements [...] {
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinTable(name = JOIN_TABLE_NAME,
joinColumns = @JoinColumn(name = COLUMN_REF_A, referencedColumnName = COLUMN_ID_A),
inverseJoinColumns = @JoinColumn(name = COLUMN_REF_B, referencedColumnName = COLUMN_ID_B))
private List<ClassB> fieldClassB;
public void addClassB(ClassB b) {
fieldClassB.add(b);
b.fieldClassA().add(this);
}
public void removeClassB(ClassB b) {
fieldClassB.remove(b);
b.fieldClassA().remove(this);
}
}