简体   繁体   中英

JPA/Hibernate: ManyToMany delete relation

I have two classes, say Group and Person with a ManyToMany-Relation that is mapped in a JoinTable.

If I delete a Person that has a relation to a Group, I want to delete the entry from the join table (not delete the group itself!).

How do I have to define the cascade-Annotations? I didn't found a really helpful documentation but several unsolved board discussions...

public class Group {
    @ManyToMany(
        cascade = { javax.persistence.CascadeType.? }, 
        fetch = FetchType.EAGER)
    @Cascade({CascadeType.?})
    @JoinTable(name = "PERSON_GROUP", 
        joinColumns = { @JoinColumn(name = "GROUP_ID") }, 
        inverseJoinColumns = { @JoinColumn(name = "PERSON_ID") })
    private List<Person> persons;    
}

public class Person {
    @ManyToMany(
        cascade = { javax.persistence.CascadeType.? },
        fetch = FetchType.EAGER, 
        mappedBy = "persons", 
        targetEntity = Group.class)
    @Cascade({CascadeType.?})
    private List<Group> group;
}

Cascade will not clean up the leftover references to the deleted Person that remain on the Group object in memory. You have to do that manually. It seems like cascade should do this, but sadly that's not the way it works.

Based on the info provided in your question, I don't think you need any cascade options set on your Person or Group entities. It doesn't sound like they share a parent/child relationship where the existence of one depends upon the other. That's the kind of relationship where I would expect to see some cascade options.

You can probably do it on a database specifically (depends on your database and it capabilities). By adding "on delete cascade" to the foreign key of the relationship table.

I believe what you want is:

cascade = CascadeType.ALL

To remove the DB relation, remove the association from each group. Remove the person from the Group.persons collection and remove the Group from the Person.group collection, then persist your person object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM