Hibernate/JPA : 当删除 child 时从多个 parents 中删除

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

我有一个具体问题,我不知道 Hibernate 是否可以自动解决:

在我们的领域模型中,我们有许多双向 One-to-many 关系,其中 "child" 可能是许多 parents 的 child。

示例:

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

我的问题是,当通过调用 entityManager.remove(node) 删除 Role - 节点时,我同时想从所有映射列表中删除 Role -refrence 以便 db 字段被适当地清空,而保留 parents 并且不在各自的列表中调用删除

这可能吗,或者这是 jpa/hibernate 的默认行为?

我敢说这会自动发生。演员和联系人列表是建立在角色对象内的外键上的——如果角色从数据库中删除,那么当 Role/Contact 在另一个会话中加载时,它将从集合中消失。实际上,父对象在其中不包含对角色的任何引用。

您应该明确地迭代联系人和参与者对象的角色列表并删除适当的角色对象。这是唯一的选择。因为它有时不会自动删除(大部分时间)。