简体   繁体   中英

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

I have Parent->Child bidirectional relationship as follows...

class Parent{

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

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

When i delete child explicitly, and after that load its parent (with all children) i get previously deleted child in children collection of parent... JPA provider is Hibernate...

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(); 

I don't understand what is the problem? Every find* method executes select (at list, those SELECTs are logged in console) , but they returns different results...

Your ManyToOne is EAGER (by default). Your OneToMany is also EAGER (you explicitely marked it so). So, when you get a child in your first line of code, JPA also loads its parent, and all the children of the parent.

Then you delete the child, but you don't remove it from the parent's chidren. And since the parent's collection of children is already loaded, the deleted child is still in the collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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