我在Parent和Child之间有很多关系。我想删除多个回答某个查询的子实体。 问题是,在运行Delete查询后,Parent.getChildren()仍然返回已删除的子项。
在这种情况下我不能使用删除查询吗?
@Entity
@Table(name = "CHILD_DATA")
public class Child {
private Parent parent;
}
@Entity
@Table(name = "PARENT")
public class Parent{
private Set<Child> children;
@Column(name = "CHILDREN")
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public Set<Child> getChildren() {
return children;
}
}
public class ChildDAO{
public int removeServiceFrontPageData(Parent parent, long serviceID){
String query = "DELETE FROM Child WHERE parent =:parent";
Query q = em.createQuery(query);
q.setParameter("parent", parent);
return q.executeUpdate();
}
}
要刷新父实体,我使用以下函数:
public class ParentDAO{
public Parent getParent(String parentID){
final String select = "FROM Parent WHERE parentID = :parentID";
Query q = em.createQuery(select);
q.setParameter("parentID", parentID);
if(q.getResultList().isEmpty()){
return null;
}
return (Parent) q.getSingleResult();
}
}
感谢
答案 0 :(得分:5)
我的解决方案基于另一个post
我找到了两种解决方法:
1)如果删除子项,则更新父项:
2)在parent.getChildren()上添加orphanRemoval = true标志。从集合中删除子项将从数据库中删除它们
@Entity
@Table(name = "PARENT")
public class Parent{
private Set<Child> children;
@Column(name = "CHILDREN")
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
public Set<Child> getChildren() {
return children;
}