JPA Cascade remove orphans

余生长醉 提交于 2019-12-25 05:55:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!