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

标签 java spring hibernate jpa spring-data-jpa

我有一个有点奇怪的问题,我不知道 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 问题

One to Many relationship JPA/Hibernate removing links

JPA 2.0 orphanRemoval=true VS on delete Cascade

关于java - 通过 JPA 中的@OneToMany 使 2 个不同的父实体引用子实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29697183/

相关文章:

javax.validation.ValidationException : HV000063: Unable to instantiate class

java - PlayFramework如何在 View 中显示java对象的详细信息

java - 进行字符串替换时的临时占位符...(Java,但通用解决方案很有用)

java - 在 Flink 数据集上应用多个 JOIN 的分区策略

java - 在原始返回类型函数上返回 "null"?

java - 在 Spring Security 中添加新用户

java - 未找到当前线程的 session (Spring 3.1.X 和 Hibernate 4)

Mysql主/从复制。即使读取查询也连接到主? (驱动程序 "ping"在去从属之前是否主控?)

java - mysql jdbc与ssl连接

java - 如何使用 JPA 和 Hibernate 在多对多关系中保存具有唯一字段的数据