问题
I have a question. I use JPA with eclipselink and I have relationship:
Table A ---< Table AB >---- Table B
class A {
@OneToMany(mappedBy = "a")
private List<AB> abList
}
class AB {
@ManyToOne(fetch = FetchType.LAZY)
private A a;
@ManyToOne(fetch = FetchType.LAZY)
private B b;
}
class B {
@OneToMany(mappedBy = "b")
private List<AB> abList;
}
It is ManyToMany relationship between A and B with join table AB. Now I want to remove a record from table A and to cascade remove records from table AB(join table) and from B table as well.
But from B only those which arent't connected to any other record from table A (many-to-many
relationship between A and B).
How should I set CascadeType or orphanremoval to do it properly?
回答1:
If you want to remove AB and B when A is deleted then just set cascade remove, (and orphanRemoval=true if you want removed instances to be removed).
If the relationship from A to B is truly ManyToMany, i.e. B can have multiple references, then you cannot cascade the remove to B, (but can still cascade to AB, ensure you maintain bi-directional relationships in your model).
There is no way to delete B if there happens to be no relationship to it from anywhere. This would be something like garbage collection, which does not exist in relational databases. You need to handle this from your application. If B is something you want to delete with A, then consider not having it shared, but have each A have its own private B instance.
回答2:
I suppose you are working with Hibernate you should make an orphanRoval=true,
after that try this: supposing we needto remove a (which class is A), we make :
for (AB ab : a.getAbList()) {
B b = ab.get();
if (b.getAbList().size()==1) {
em.remove(b);
}
em.remove(ab);
}
em.remove(a);
Hope this help
来源:https://stackoverflow.com/questions/17018302/jpa-cascade-remove-orphans