由於匯入excel插入資料,遍歷方式插入資料非常慢,所以修改成批次插入資料,程式碼如下:
批次插入配置類
@Repository
public class BatchData {
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
public void saveList(String statement, List<? extends Object> datas){
doUpdateList(statement,datas);
}
private void doUpdateList(String statement, List<? extends Object> datas){
if(datas==null||datas.size()==0){
return;
}
final int batchSize=100;
SqlSession sqlSession=sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
try {
int i=0;
for (Object data : datas){
sqlSession.update(statement,data);
i++;
if(i%batchSize==0){
sqlSession.flushStatements();
sqlSession.commit();
sqlSession.clearCache();
}
}
if(i%batchSize!=0){
sqlSession.flushStatements();
sqlSession.commit();
sqlSession.clearCache();
}
}finally {
sqlSession.close();
}
}
}
業務程式碼實現類
@Service
public class BatchDataServiceImpl implements IBatchDataService {
private static final String mapperNs=BatchDataMapper.class.getCanonicalName();
@Override
public void saveList(List<BatchDataEntity> datas){
batchData.saveList(mapperNs+".insert",datas);
}
}