JPA Hibernate cascade type for child of child

会有一股神秘感。 提交于 2021-01-29 06:44:42

问题


I was looking for documentation or answer how will the cascade work for child of child , example :

public class Parent{
  @OneToMany(fetch = FetchType.EAGER,mappedBy = "parent",cascade = CascadeType.ALL)
  private List<Child> child;
}

public class Child{
     @OneToMany(mappedBy="child")
      private List<AnotherChild> anohterChild;
    }
  @ManyToOne
    private Parent parent;
}

now the question, will the cascade operation applied on "Child" from parent class apply to "AnotherChild" ? in other words if I persist "Parent" Object will it persist "AnotherChild" ?


回答1:


If you persist your parent, only those childs which are in the child-list of your parent-class get persisted but not the list of AnotherChilds in your child-class.

If you wish to persist them too just cascade it too:

public class Child{
     @OneToMany(mappedBy="child", cascade = CascadeType.PERSIST)
     private List<AnotherChild> anohterChild;

     @ManyToOne
     private Parent parent;
}

And just use CascadeType.ALLwhen you really need it, because this cascade-type includes more than just persisting. As it is explained in the following picture, CascadeType.ALL includes all other cascade-types including the cascade-type "remove" which means that, when your parent-object gets removed, all other child-objects get removed too.



来源:https://stackoverflow.com/questions/49468371/jpa-hibernate-cascade-type-for-child-of-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!