korgmatose
korgmatose

Reputation: 265

Hibernate/JPA : Remove from multiple parents when child is deleted

I have a specific issue that I don't know if Hibernate can automatically resolve:

In our domain model, we have many bidirectional One-to-many relationships, where the "child" might be a child of many parents.

Example:

public Class Role {

    @ManyToOne(targetEntity = Actor.class, fetch = FetchType.LAZY)
    private Actor actor;

    @ManyToOne(targetEntity = Contact.class, fetch = FetchType.LAZY)
    private Contact contact;
}

public class Actor {

    @OneToMany(targetEntity = Role.class, fetch = FetchType.LAZY)
    private List<Role> roles;
} 
public class Contact {

    @OneToMany(targetEntity = Role.class, fetch = FetchType.LAZY)
    private List<Role> roles;
} 

The question I have, is that when removing a Role - node by calling entityManager.remove(node), I simultaneously want to remove the Role -refrence from all the mapped lists so that the db fields gets nulled appropriately, while KEEPING the parents and not calling remove on their respective Lists

Is this possible, or is this the default behaviour of jpa/hibernate?

Upvotes: 1

Views: 671

Answers (2)

Hakuna Matata
Hakuna Matata

Reputation: 763

you should explicitly iterate the contact and actor object's role lists and remove the appropriate role object. That is the only option. Because it wont remove automatically sometime (Most of the time).

Upvotes: 2

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

I daresaay this will happen automagically. Actor and contact lists are build on foreign keys inside role object - if role is removed from db then it will dissapear from collections when Role/Contact are loaded in another session. Actually parent objects do not hold any reference in them to the Role.

Upvotes: 1

Related Questions