问题
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.ALL
when 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