ESala
ESala

Reputation: 7058

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

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

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

What I would like to do, is have a @OneToMany relationship between Parent1 and Child, and another @OneToMany relationship between Parent2 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 can't get it to work...

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

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 you,

Upvotes: 4

Views: 2246

Answers (3)

Predrag Maric
Predrag Maric

Reputation: 24423

You will have to handle this on service/DAO level, I don't think you'll find any JPA support for this specific use case. Just manually check the conditions prior to deleting the parent/child.

Upvotes: 0

Dev
Dev

Reputation: 2325

Yes as per @jmvivo answer you need to use orphanRemoval=true is solution of your use-case , Here As per Oracle On this 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.

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

One to Many relationship JPA/Hibernate removing links

JPA 2.0 orphanRemoval=true VS on delete Cascade

Upvotes: 1

jmvivo
jmvivo

Reputation: 2663

Reading OneToMany.ophanRemoval, you can try this:

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

Good luck!

Upvotes: 1

Related Questions