Spring Hibernate saveAndFlush()需要很长时间才能按行插入10K
我是一个冬眠新手。我有以下代码,它保存了Spring Hibernate saveAndFlush()需要很长时间才能按行插入10K,spring,hibernate,jpa,spring-data,Spring,Hibernate,Jpa,Spring Data,我是一个冬眠新手。我有以下代码,它保存了列表中的大量行(比如10K行): @覆盖 @事务(只读=假) public void createParticipantsAccounts(长studyId,列表主体ID)引发异常{ StudyT study=studyDAO.getStudyByStudyId(studyId); Authentication auth=SecurityContextHolder.getContext().getAuthentication(); 对于(字符串subjec
列表中的大量行(比如10K行):
@覆盖
@事务(只读=假)
public void createParticipantsAccounts(长studyId,列表主体ID)引发异常{
StudyT study=studyDAO.getStudyByStudyId(studyId);
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
对于(字符串subjectId:subjectId){//循环,每个循环使用saveAndFlush()
// ...
user.setRoleTypeId(4);
user.setActiveFlag(“Y”);
user.setCreatedBy(auth.getPrincipal().toString().toLowerCase());
setCreatedDate(新日期());
列表参与者=新建ArrayList();
StudyParticipantsT sp=新的StudyParticipantsT();
sp.setStudyT(研究);
sp.setUsersT(用户);
sp.setsubjected(主语);
sp.setLocked(“N”);
sp.setCreatedBy(auth.getPrincipal().toString().toLowerCase());
sp.setCreatedDate(新日期());
参与者。添加(sp);
user.setStudyParticipantsTs(参与者);
userDAO.saveAndFlush(用户);
}
}
}
但此操作耗时太长,对于10K行,大约需要5-10分钟。改善这一点的正确方法是什么?我真的需要用批插入重写整个过程吗,还是有什么简单的东西可以修改
注意我还尝试了不使用刷新的userDAO.save()
,并在for循环外的末尾尝试了userDAO.Flush()
。但这没有帮助,同样糟糕的性能。我们解决了它批量插入通过saveAll
完成。我们定义一个批量大小,比如1000,然后saveAll
列表,然后重置。如果在最后(一个边缘条件),我们也保存。这大大加快了所有插入的速度
int batchSize = 1000;
// List for Batch-Inserts
List<UsersT> batchInsertUsers = new ArrayList<UsersT>();
for(int i = 0; i < subjectIds.size(); i++) {
String subjectId = subjectIds.get(i);
UsersT user = new UsersT();
// Fill out the object here...
// ...
// Add to Batch-Insert List; if list size ready for batch-insert, or if at the end of all subjectIds, do Batch-Insert saveAll() and clear the list
batchInsertUsers.add(user);
if (batchInsertUsers.size() == maxBatchSize || i == subjectIds.size() - 1) {
userDAO.saveAll(batchInsertUsers);
// Reset list
batchInsertUsers.clear();
}
}
int batchSize=1000;
//批量插入的列表
列出batchInsertUsers=new ArrayList();
for(int i=0;i
我们解决了它批量插入通过saveAll
完成。我们定义一个批量大小,比如1000,然后saveAll
列表,然后重置。如果在最后(一个边缘条件),我们也保存。这大大加快了所有插入的速度
int batchSize = 1000;
// List for Batch-Inserts
List<UsersT> batchInsertUsers = new ArrayList<UsersT>();
for(int i = 0; i < subjectIds.size(); i++) {
String subjectId = subjectIds.get(i);
UsersT user = new UsersT();
// Fill out the object here...
// ...
// Add to Batch-Insert List; if list size ready for batch-insert, or if at the end of all subjectIds, do Batch-Insert saveAll() and clear the list
batchInsertUsers.add(user);
if (batchInsertUsers.size() == maxBatchSize || i == subjectIds.size() - 1) {
userDAO.saveAll(batchInsertUsers);
// Reset list
batchInsertUsers.clear();
}
}
int batchSize=1000;
//批量插入的列表
列出batchInsertUsers=new ArrayList();
for(int i=0;i