Make 2 different parent objects a reference to child object via @OneToMany in JPA

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

I have @Entity Child

two other objects, @Entity Parent1

and @Entity Parent2

.

What I would like to do is there is a relationship @OneToMany

between parent and child, and another relationship @OneToMany

between parent and child.

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 cannot get it to work ...

TL; DR : Any child that has no parent1 and parent2 should be removed.

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

      

Thank,

+3


source to share


3 answers


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

When a target in a one-to-one or one-to-many relationship is removed from the relationship, it is often desirable to cascade the delete operation to the target. Such targets are considered orphaned, and the orphanRemoval attribute can be used to indicate that orphaned objects should be removed. For example, if there are many items in an order and one of them is removed from the order, the deleted item is considered an orphan. If the orphanRemoval parameter is set to true, the item object will be removed when the item is removed from the order.

You can also look below SO Question how you go further with your requirement



JPA / Hibernate One-to-Many Relationships Remove References

JPA 2.0 orphanRemoval = true VS to remove cascade

+1


source


Reading OneToMany.ophanRemoval , you can try this:

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

      



Good luck!

+1


source


You will have to handle this in the service / DAO layer, I don't think you will find JPA support for this particular use case. Just manually check the conditions before removing the parent / child.

0


source







All Articles