我有一个有点奇怪的问题,我不知道 JPA 是否支持这个:
我有一个 @Entity Child
和另外两个实体,@Entity Parent1
和 @Entity Parent2
。
我想做的是,在 Parent1 和 Child 之间建立一个 @OneToMany
关系,在 Parent2 和 Child 之间建立另一个 @OneToMany
关系。
原因是我希望删除 Parent1 时删除 Childs,删除 Parent2 时删除 Childs。
我尝试了很多组合,但我无法让它工作...
TL;DR:任何没有 Parent1 和 Parent2 的 Child 都应该被删除。
现在这是我的代码(省略了@Id 和 getter/setter):
@Entity
class Parent1 {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
Set<Child> childs;
}
@Entity
class Parent2 {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
Set<Child> childs;
}
@Entity
class Child {
String name;
}
谢谢,
最佳答案
是的,根据@jmvivo 的回答,您需要使用 orphanRemoval=true 来解决您的用例, 这里根据 Oracle 在此 link
When a target entity in one-to-one or one-to-many relationship is removed from the relationship, it is often desirable to cascade the remove operation to the target entity. Such target entities are considered “orphans,” and the orphanRemoval attribute can be used to specify that orphaned entities should be removed. For example, if an order has many line items and one of them is removed from the order, the removed line item is considered an orphan. If orphanRemoval is set to true, the line item entity will be deleted when the line item is removed from the order.
您可能还想在进一步满足您的要求时查看下面的 SO 问题
关于java - 通过 JPA 中的@OneToMany 使 2 个不同的父实体引用子实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29697183/