【发布时间】:2020-02-16 23:43:54
【问题描述】:
我是 Hibernate 新手。我有以下代码仍然存在于List<String>:
@Override
@Transactional(readOnly = false)
public void createParticipantsAccounts(long studyId, List<String> subjectIds) throws Exception {
StudyT study = studyDAO.getStudyByStudyId(studyId);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
for(String subjectId: subjectIds) { // LOOP with saveAndFlush() for each
// ...
user.setRoleTypeId(4);
user.setActiveFlag("Y");
user.setCreatedBy(auth.getPrincipal().toString().toLowerCase());
user.setCreatedDate(new Date());
List<StudyParticipantsT> participants = new ArrayList<StudyParticipantsT>();
StudyParticipantsT sp = new StudyParticipantsT();
sp.setStudyT(study);
sp.setUsersT(user);
sp.setSubjectId(subjectId);
sp.setLocked("N");
sp.setCreatedBy(auth.getPrincipal().toString().toLowerCase());
sp.setCreatedDate(new Date());
participants.add(sp);
user.setStudyParticipantsTs(participants);
userDAO.saveAndFlush(user);
}
}
}
但是这个操作耗时太长,大概5-10分钟。 10K 行。改善这种情况的正确方法是什么?我真的需要用批量插入重写整件事吗?或者有什么简单的我可以调整?
注意我还尝试了不使用 Flush 的 userDAO.save(),并在 for 循环外的末尾尝试了 userDAO.flush()。但这并没有帮助,同样糟糕的表现。
【问题讨论】:
标签: spring hibernate jpa spring-data