Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 598
tautologe Avatar asked Nov 18 '10 18:11

tautologe


1 Answers

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.

like image 173
Jim Tough Avatar answered Sep 19 '22 16:09

Jim Tough