首页 > 代码库 > jpa 批量插入

jpa 批量插入

@Override
@Transactional
public <S extends E> List<S> save(Iterable<S> entities) {
List<S> result = new ArrayList<>();
if (entities == null) {
return result;
}
Iterator<S> iterator = entities.iterator();
int i = 0;
int count = 0;
//遍历循环 每20个(可以做成配置中读取) insert 批量插入一次库
while (iterator.hasNext()) {
S entity = iterator.next();
entityManager.persist(entity);
result.add(entity);
i++;
if (i % 20 == 0) {
entityManager.flush();
entityManager.clear();
count=0;
}else {
count++;
}
}
//判断 是否有剩余未flush的 最后flush
if (count>0){
entityManager.flush();
entityManager.clear();
}
return result;
}
https://github.com/Alexey-/spring-boot-batch/blob/master/src/main/resources/application.properties

jpa 批量插入