JPA级联删除孤儿 [英] JPA Cascade remove orphans

查看:180
本文介绍了JPA级联删除孤儿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.我将JPA与eclipselink一起使用,并且有关系:

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;
}

A和B与连接表AB之间是ManyToMany关系. 现在,我想从表A中删除一条记录,并从表AB(联接表)和B表中级联删除记录.

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.

但是从B中只有那些没有连接到表A中的任何其他记录的记录(A和B之间的many-to-many关系).

But from B only those which arent't connected to any other record from table A (many-to-many relationship between A and B).

我应该如何设置CascadeType或orphanremoval使其正确执行?

How should I set CascadeType or orphanremoval to do it properly?

推荐答案

如果要在删除A时删除AB和B,则只需设置级联删除(如果要删除已删除的实例,则设置为orphanRemoval = true).

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).

如果从A到B的关系确实是ManyToMany,即B可以有多个引用,那么您不能将remove层叠到B,(但是仍然可以层叠到AB,请确保您在模型中保持双向关系).

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).

如果从任何地方碰巧与B都没有关系,则无法删除B.这就像垃圾回收一样,在关系数据库中不存在.您需要从您的应用程序中处理此问题.如果您要与A一起删除B,请考虑不共享它,但让每个A拥有自己的私有B实例.

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.

这篇关于JPA级联删除孤儿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆