Spring Data Jpa-ManyToMany-删除联接表的实体 [英] Spring Data Jpa - ManyToMany - delete entities of the join table
问题描述
我有这两节课:
public class ClassA extends [...] implements [...] {
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@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 class ClassB extends [...] implements [...] {
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "fieldClassB", cascade = CascadeType.ALL)
private List<ClassA> fieldClassA;
}
当我(通过spring数据jpa存储库)删除 ClassB
时,Hibernate也会删除 ClassA
的实例,而我只希望 JOIN_TABLE_NAME
表中删除(另一个问题是,由于级联模式,删除 ClassA
实体还会删除这些 ClassA
).
When I delete ClassB
(via the spring data jpa repository), Hibernate also deletes instances of ClassA
, whereas I just want the rows in the JOIN_TABLE_NAME
table to be deleted (the other issue is that, due to the cascade mode, deleting the ClassA
entities also delete other ClassB
referenced by these ClassA
).
有什么方法可以解决这个问题,而不必创建联接实体并用引用新联接实体的 @OneToMany
替换 @ManyToMany
批注?
Is there any way to handle this without having to create the join entity and to replace the @ManyToMany
annotations by @OneToMany
referencing the new join entity ?
推荐答案
级联在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几乎总是对manyToMany不好,因为它最终不仅删除了关联表中的内容.
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);
}
}
这篇关于Spring Data Jpa-ManyToMany-删除联接表的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!