JPA(带游戏!)双向多对多-如何从关系的双方移除?

JPA(带游戏!)双向多对多-如何从关系的双方移除?,jpa,many-to-many,constraints,playframework,cascading-deletes,Jpa,Many To Many,Constraints,Playframework,Cascading Deletes,我的游戏中有以下映射!使用JPA的应用程序: @Entity public class Contact extends Model { public String name; @ManyToMany(mappedBy = "contacts", fetch = FetchType.EAGER) public Set<Category> categories = new HashSet<Category>(); publi

我的游戏中有以下映射!使用JPA的应用程序:

@Entity
public class Contact extends Model {        
    public String name;

    @ManyToMany(mappedBy = "contacts", fetch = FetchType.EAGER)
    public Set<Category> categories = new HashSet<Category>();

    public void addCategory(Category c) {
        this.categories.add(c);
        if (!c.contacts.contains(this)) {
            c.contacts.add(this);
        }
    }

    @PreRemove
    public void preRemove() {
        for (Category c : this.categories) {
            c.contacts.remove(this);
        }
        this.categories = null;
    }
}

@Entity
public class Category extends Model {
    public String name;

    @ManyToMany
    public Set<Contact> contacts = new HashSet<Contact>();

    public void addContact(Contact c) {
        this.contacts.add(c);
        if (!c.categories.contains(this)) {
            c.categories.add(this);
        }
    }

    @PreRemove
    protected void preRemove() {
        for (Contact c : this.contacts) {
            c.categories.remove(this);
        }
        this.contacts = null;
    }
}
如何确保删除联系人不会删除类别,而只会删除关系

编辑:嘘!问题是我还有一个用户对象,它同时引用了Contact和Category。我没有理清这段关系。以下是对Contact类中preRemove()方法的更改:

@PreRemove
public void preRemove() {
    for (Category c : this.categories) {
        c.contacts.remove(this);
    }

    this.user.contacts.remove(this);
    for (Category c : this.user.categories) {
        c.contacts.remove(this);
    }
    //It's important to save the user 
    this.user.save();
}

另一种解决方案是在删除主图元之前,手动从列表中删除图元并保存:

while( !contact.categories.isEmpty() ) {  
    contact.categories.remove(0);  
}  
contact.save();  
contact.delete();

另一种解决方案是在删除主图元之前,手动从列表中删除图元并保存:

while( !contact.categories.isEmpty() ) {  
    contact.categories.remove(0);  
}  
contact.save();  
contact.delete();