如何正确保存具有一对多关系的实体?

时间:2018-12-12 19:36:25

标签: java spring spring-data-jpa

我正在使用spring jpa。

我有两个具有一对多关系的实体:

class Parent {
  @ID
  @Generated
  Integer id;

  @OneToMany
  Set<Child> children

}

class Child {
  @ID
  @Generated
  Integer id;

  @ManyToOne
  Parent parent;
}

根据我对jpa关系的理解,我们可以保存父类,而JPA会自动保存其相关的子级。所以我把下面的用法代码放在一起:

Parent parent1 = new Parent("David");

Child child1 = new Child("Jack");
Child child2 = new Child("Mary");
Set<Child> children = new HashSet<>();
children.add(child1);
children.add(child2);
// I purposely skipped saving each child, to rely on the saving operation of the parent 
// for child in children {
//  child = childJpaRepository.save(child);
// }


// I expect that saving parent will update each children's generated-ID
parent = parentJpaRepository.save(parent); 

我尝试了上面的代码,发现如果我在上面的代码之后执行此操作,则每个孩子的id字段都保持未设置状态

for child in children {
  print(child.getId());
}

我的问题:保存这种关系的正确方法是什么?保存父项之前,我必须执行以下声明吗?

 for child in children {
  child = childJpaRepository.save(child);  // ??? Isn't it slow to do individual saving of each child, because DB operation is high cost??
 }

0 个答案:

没有答案