JPA级联删除孤儿

编程入门 行业动态 更新时间:2024-10-23 20:20:58
本文介绍了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级联删除孤儿

本文发布于:2023-10-16 05:48:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:孤儿   级联   JPA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!