gpt4 book ai didi

java - spring boot jpa - 生成并保存测试数据

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:04 25 4
gpt4 key购买 nike

我试图用大量测试数据填充我的数据库,因此我编写了一个 CommandLineRunner 来保存大约 2k 个实体。

它有效 - 但需要永远完成(5-10 分钟) - 我处理这个问题的方式是错误的吗?

@Component
public class DbSeederTest implements CommandLineRunner {

@Autowired
FirstRepo firstRepo;
@Autowired
SecondRepo secondRepo;
@Autowired
ThirdRepo thirdRepo;

private List<FirstEnt> firstList = new ArrayList<>();
private List<SecondEnt> secondList = new ArrayList<>();
private List<ThirdEnt> thirdList = new ArrayList<>();


private void generateTestData() {
// generate alot of entities, and add them to the Lists
}

@Override
public void run(String... args) throws Exception {

System.out.println("saving ents...");

generateTestData();

try {

firstRepo.save(firstList);
secondRepo.save(secondList);
thirdRepo.save(thirdList);

} catch(Exception e) {
e.printStackTrace();
}

}
}

最佳答案

您可以尝试利用批量插入功能。

有一个 hibernate 属性,您可以将其定义为 hibernate 的 SessionFactory 的属性之一:

<property name="jdbc.batch_size">250</property>

使用此批处理设置,您应该得到如下输出:

插入 Table(id , name) 值 (1, 'na1') , (2, 'na2') ,(3, 'na3')。

而不是

insert into Table(id , name) values (1, 'na1');
insert into Table(id , name) values (2, 'na2');
insert into Table(id , name) values (3, 'na3');

在您的存储库保存方法中,您将保留大约 250 个(您必须做一些测试应用程序性能方面的最佳点)实体..然后刷新您的 session 以获得最佳性能,直到保存所有数据:

public void save(List<Item> itemList){
for ( int i=0; i<itemList.size(); i++ ) {
session.save(itemList.get(i));

if ( i % 250 == 0 ) { //250, same as the JDBC batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
}

关于java - spring boot jpa - 生成并保存测试数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42248732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com