Hibernate PersistentSet remove() operation not wor

2019-02-22 12:22发布

问题:

I've a Set in my Parent entity as below:

Class Parent {
 @OneToMany(mappedBy = parent, cascade = CasacadeType.ALL)
 Set<Child> children;
}

Class Child {
 @Column(nullable=false)
 @ManyToOne
 Parent parent;
}

Now event if I do a remove() operation on the Set for one of its element it doesn't actually get removed.

回答1:

Your mapping should look like this:

public class Parent { 
    @OneToMany(mappedBy = parent, cascade = CasacadeType.ALL, orphanRemoval = true) 
    Set<Child> children;

    public void removeChild(Child child) {
        children.remove(child);
        child.setParent(null);
    }
}

public class Child {
    @ManyToOne
    Parent parent; 
}

As explained in this article, because you have a bidirectional association you have to have both sides in-sync.

Therefore, it's good practice to call:

parent.removeChild(child);

This way, removeChild is going to remove the Child from the children Set and also set the Child's parent association to null.



回答2:

I had same problem and although using remove and setParent to null, related data was at db still. After debugging I saw related child object couldn't been removed from parent's child list. When I searched "hibernate set remove not working" at net, I found the hibernate truth: remove method has some bug because hashcode and equals methods. After seing that I think maybe removeAll() method could work properly. I put related one object to list and put list to removeAll method and it succeeded. As an example:

List childList = new ArrayList();
childList.add(child);
parent.removeAll(childList);
child.setParent(null);