Hibernate + Spring JPA:双向oneToMany触发两次插入查询

时间:2018-08-10 01:46:06

标签: hibernate spring-boot jpa

在spring boot应用程序中,我有父子实体。父母有很多孩子。父级为子级列表定义了oneToMany,而子级为父级对象定义了manyToOne。当我尝试插入时,日志显示每次插入都会触发两次查询。

Parent.java

public class Parent {

  @javax.persistence.Id
  @Column(name = "PARENT_ID")
  //sequence generator
  private Long parentId;

  @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
  private List<Child> childs;

//getters and setters
}

Child.java

public class Child {

  //constructor

  @javax.persistence.Id
  @Column(name = "CHILD_ID")
  //sequence generator
  private Long childId;

  @Column(name="NAME")
  private String childName;

  @ManyToOne
  @JoinColumn(name="PARENT_ID")
  Parent parent;

  //getters and setters
}

存储库调用

Parent p = new Parent();
List<Child> childs = Arrays.asList(new Child("child1", p), new 
Child("child2", p));
p.setChilds(childs);

//call to save entity
parentRepository.save(p);

当我执行此语句时,我看到2条select语句,2条针对父级的插入语句,4条针对子级的插入语句。我的期望是给父母插入1个,给孩子插入2个。

这是应该的样子还是我做错了什么?

0 个答案:

没有答案