保存具有一对多映射的多个实体会导致动态数据库调用

问题描述 投票:0回答:1

让两个实体:School(id,name)和Student(id,name,SchoolId)。从学生到学校存在一对多映射。用于在 Spring boot 中保存学生列表:

public void saveStudents(List<Student> studentList, School school){
        for(Student student: studentList){
               student.setSchool(school);
        }
        studentRepositor.saveAll(studentList)
}

对于 1000 名学生的列表,这

saveAll()
会导致 1000 次 db 调用,这是昂贵的。如何有效地做到这一点?

我尝试过使用

spring.jpa.properties.hibernate.order_inserts=true 
进行批量插入,在此处注明。 但这会导致更高的延迟,而且如果列表大小增加,批量调用和延迟时间也会增加。

我怎样才能有效地做到这一点?

实际上,我必须将某些学生复制到具有不同id的学生表中,以及学校表中相应的学校。我可以通过本机查询来完成此操作,但这会违反与数据库无关的功能。有人可以在这方面帮助我吗?

两个实体:

@Entity
@Table(name = "school")
public class School extends BaseEntity {

  @Id
  @Column(name = "id", nullable = false, length = 128)
  private String id;

  @DiffIgnore
  @OneToMany(mappedBy = "school", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, orphanRemoval = true)
  private Set<Student> students;
  }

和学生:

@Entity
@Table(name = "student")
public class Student extends BaseEntity {

  @Id
  @Column(name = "id", nullable = false, length = 128)
  private String id;
  
  @ShallowReference
  @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
  @JoinColumn(name = "school_id", referencedColumnName = "id", nullable = false)
  private School school;
}
java sql-server spring-boot hibernate spring-data-jpa
1个回答
0
投票

如果性能是主要关注点,我建议尝试一下 spring jpa Hibernate 的以下属性

spring.jpa.properties.hibernate.jdbc.batch_size=250. # or whatever you would like
spring.jpa.properties.hibernate.order_inserts=true # you already have this

saveAll()
使用批处理仍然比
save()
更高效,原因之一是只会为批次创建一个事务。

© www.soinside.com 2019 - 2024. All rights reserved.