A collection with cascade=“all-delete-orphan” was no longer referenced by the owning entity instance

后端 未结 5 1222
终归单人心
终归单人心 2021-02-01 07:26

In my application, a hibernate operation goes like this. The application updates a parent entity with new values from the request and deletes all the existing (previously insert

相关标签:
5条回答
  • 2021-02-01 08:08

    instead of setChilds use addAll ,

    from this,

        parent.getChilds().clear();
        parent.setChilds(newChilds);
    

    to

        parent.getChilds().clear();
        parent.getChilds().addAll(newChilds);
    
    0 讨论(0)
  • 2021-02-01 08:15

    It worked for me.

    1. Cleared all my child entities.
    2. Instead of setting the new child entities to my parent object, I have used addAll method to add the new child entities.

      parent.getChildren().clear();
      parent.getChildren().addAll(newChildrenList);
      
      @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, 
                 cascade = CascadeType.ALL, orphanRemoval = true)  
      
      public Set<Children> getChildren() {
          return this.children;
      }
      
    0 讨论(0)
  • 2021-02-01 08:20

    Your last snippet of Java code doesn't compile. I guess it looks like

    parent.getChilds().clear(); // note: you should name it children rather than childs
    parent.setChilds(someNewSetOfChildren):
    

    Don't do the last instruction. Instead of replacing the set by another one, clear the set and add the new children to the cleared set:

    parent.clearChildren();
    parent.addChildren(someNewSetOfChildren);
    

    where the methods are defined as:

    public void clearChildren() {
        this.children.clear();
    }
    
    public void addChildren(Collection<Child> children) {
        this.children.addAll(children);
    }
    

    The setChildren method should be removed completely, or it should be replaced with the following implementation:

    public void setChildren(Collection<Child> children) {
        this.children.clear();
        this.children.addAll(children);
    }
    
    0 讨论(0)
  • 2021-02-01 08:22

    I faced the same issue and get it solved as follows:

    1- add {CascadeType.ALL}, orphanRemoval=true in all @OneToMany annotations in all entity Childs of that element.

    2- Check the hashcode() and equalls() of those entities, some times they have erros

    3- Don't use parent.setChilds(newChilds); as the engine will ask for missing the reference to the childs, but use instead use

    parent.getChilds().clear();
    parent.getChilds().add(Child);
    

    or

    parent.getChilds().addAll(Childs);
    

    Those steps solved my issue after 4 Hours of research

    0 讨论(0)
  • 2021-02-01 08:26

    it change works !

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "user_id")
    private List<Role> roles;
    
    0 讨论(0)
提交回复
热议问题