我是Hibernate的新手,我有以下问题:
说我有以下情况:
@Entity
public class Parent(){
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PID")
private Long id;
@OneToOne(mappedBy = "Parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Child child;
}
@Entity
public class Child()implements Serializable {
@Id
private Long id;
@OneToMany(
mappedBy = "child",
cascade = {CascadeType.ALL, CascadeType.PERSIST, CascadeType.MERGE},
orphanRemoval = true
)
private List<Grandchild> grandchilds;
@OneToOne(fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.REMOVE)
@MapsId()
@JoinColumn(name = "PID")
@Cascade(org.hibernate.annotations.CascadeType.DELETE)
private Parent parent;
}
@Entity
@IdClass(GrandchildID.class)
public class Grandchild {
@Id
@Column(name = "AID")
private Long aid;
@Id
@Column(name = "GID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long gid;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL, CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "AID")
@MapsId("AID")
private Child child;
}
我有一个问题:
我知道休眠可以保存级联数据。
因此我可以执行以下操作:
for each grandchild{
grandchild.setChild(child);
}
child.setGrandChilds = (grandchilds);
child = childRepository.save(child);//which will save both child and grandchild.
parent.setChild(child);
parentRepository.save(parent)//which will save parent
我的问题是:
为什么我需要先保存孩子?
为此,由于保存子代也将自动为我保存孙子代,因此Hibernate看起来可以为我同时保存这两个子代。 那么,为什么我不能只保存父母,以便休眠状态可以为我自动保存孩子和孙子? 冬眠仅自动为孩子自动保存(不为孙子自动保存)吗?