要确保子实体在保存父实体时被持久化,可以使用级联的方式进行保存,即在父实体上加上CascadeType.PERSIST或CascadeType.ALL属性,例如:
@Entity public class Parent { @Id private Long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
private List children;
// getter和setter方法省略
}
@Entity public class Child { @Id private Long id;
@ManyToOne
private Parent parent;
// getter和setter方法省略
}
在保存父实体时,该代码将同时保存子实体:
Parent parent = new Parent(); Child child1 = new Child(); child1.setParent(parent); parent.setChildren(Arrays.asList(child1)); entityManager.persist(parent);