通过 JPA 中的@OneToMany 使 2 个不同的父实体引用子实体

Make 2 different Parent Entities reference a Child Entity through @OneToMany in JPA

有个奇怪的问题,不知道JPA是否支持:

我有一个 @Entity Child 和另外两个实体,@Entity Parent1@Entity Parent2

我想做的是,在 Parent1 和 Child 之间建立 @OneToMany 关系,在 Parent2 和 Child 之间建立另一个 @OneToMany 关系。

原因是我想删除Childs的Parent1也删除,删除Childs的Parent2也删除。

我尝试了很多组合,但我无法让它工作...

TL;DR:任何没有 Parent1 和 Parent2 的 Child 都应该被删除。

这是我现在的代码(忽略@Id 和 getter/setters):

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

谢谢,

阅读OneToMany.ophanRemoval,你可以试试这个:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval=true)
Set<Child> childs;

祝你好运!

是的,根据@jmvivo 的回答,您需要使用 orphanRemoval=true 来解决您的用例, Here As per 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 问题

One to Many relationship JPA/Hibernate removing links

JPA 2.0 orphanRemoval=true VS on delete Cascade

您必须在 service/DAO 级别处理此问题,我认为您不会找到任何 JPA 支持此特定用例。只需在删除 parent/child.

之前手动检查条件