Hibernate PersistentSet remove()操作不起作用

我在我的父实体中有一个Set,如下所示:

Class Parent { @OneToMany(mappedBy = parent, cascade = CasacadeType.ALL) Set children; } Class Child { @Column(nullable=false) @ManyToOne Parent parent; } 

现在事件,如果我对其中一个元素的Set执行remove()操作,它实际上不会被删除。

您的映射应如下所示:

 public class Parent { @OneToMany(mappedBy = parent, cascade = CasacadeType.ALL, orphanRemoval = true) Set children; public void removeChild(Child child) { children.remove(child); child.setParent(null); } } public class Child { @ManyToOne Parent parent; } 

正如本文所述 ,由于您具有双向关联,因此您必须使双方同步。

因此,最好打电话:

 parent.removeChild(child); 

这样, removeChild将从children集中删除Child ,并将Childparent关联设置为null

我有同样的问题,虽然使用remove和setParent为null,相关数据仍然在db。 调试后,我看到无法从父项的子列表中删除相关的子对象。 当我在网上搜索“hibernate set remove not working”时,我发现了hibernate真相:remove方法有一些bug,因为hashcode和equals方法。 在seing之后我认为removeAll()方法可能正常工作。 我把相关的一个对象放到列表中并将列表放到removeAll方法中并且它成功了。 举个例子:

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