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
posted @ 2017-08-07 11:33  托马斯布莱克  阅读(3010)  评论(0编辑  收藏  举报