繁体   English   中英

Spring Data JPA-在显式删除子级后加载父级将返回具有已删除子级的子级的集合

[英]Spring Data JPA - loading parent after explicit child deletion returns collection of children with deleted child

我有如下的父/子双向关系...

class Parent{

    @OneToMany(mappedBy="parent", fetch = FetchType.EAGER)
    Collection<Child> children;
}

class Child{
    @ManyToOne
    @JoinColumn(name="PARENT_ID")
    private Parent parent;
}

当我显式删除子级后,在加载其父级(包括所有子级)后,我在父级的子级集合中得到了先前删除的子级。JPA提供程序是休眠的。

Child child= childRepo.findOne(CHILD_ID);

childRepo.delete(child);
childRepo.flush();

// next, returns collection without deleted child
Collection<Child> children= childRepo.findAll(); 

Parent parent = parentRepo.findById(PARENT_ID);

/// next, returns collection including deleted child
Collection<Child> parentChildren = parent.getChildren(); 

我不明白是什么问题? 每个find *方法都执行select(在列表中,这些SELECT被记录在控制台中),但是它们返回不同的结果...

您的ManyToOne是EAGER(默认情况下)。 您的OneToMany也是EAGER(您已明确标记为)。 因此,当您在代码的第一行中生了一个孩子时,JPA还将加载其父对象以及该父对象的所有孩子。

然后,您删除了孩子,但没有将其从父母的孩子中删除。 并且由于已经加载了父级的子级集合,因此删除的子级仍在集合中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM