通过JPA中的@OneToMany,使2个不同的父实体引用一个子实体 [英] Make 2 different Parent Entities reference a Child Entity through @OneToMany in JPA

查看:156
本文介绍了通过JPA中的@OneToMany,使2个不同的父实体引用一个子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a somewhat strange question, I don't know if this is supported in JPA:

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

I have an @Entity Child and two other entities, @Entity Parent1 and @Entity Parent2.

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

What I would like to do, is have a @OneToMany relationship between Parent1 and Child, and another @OneToMany relationship between Parent2 and Child.

原因是我希望删除Childs的Parent1被删除,而希望Childs的Parent2被删除.

The reason is that I want Childs to be deleted if their Parent1 is deleted, and Childs to be deleted if their Parent2 is deleted.

我尝试了很多组合,但无法正常工作...

I have tried many combinations but I can't get it to work...

TL; DR :应删除任何没有Parent1和Parent2的孩子.

TL;DR: Any Child that does not have a Parent1 AND a Parent2 should be deleted.

这是我的代码(省略@Id和getter/setter):

Here is my code right now (ommitting @Id and 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;
}

谢谢

推荐答案

是的,按照@jmvivo的回答,您需要使用orphanRemoval = true是您的用例解决方案, 根据Oracle在此链接

Yes as per @jmvivo answer you need to use orphanRemoval=true is solution of your use-case , Here As per Oracle On this link

从关系中删除一对一或一对多关系的目标实体时,通常需要将删除操作级联到目标实体.此类目标实体被视为孤立的",并且orphanRemoval属性可用于指定应删除孤立的实体.例如,如果订单中有很多订单项,并且其中一个订单已从订单中删除,则删除的订单项将被视为孤立订单项.如果orphanRemoval设置为true,则从订单中删除订单项时,订单项实体将被删除.

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

You might also want to look at below SO Question as you go further with your requirement

一对多关系JPA/Hibernate删除链接

在删除Cascade上的JPA 2.0 orphanRemoval = true VS

这篇关于通过JPA中的@OneToMany,使2个不同的父实体引用一个子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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