mybatis 批量插入数据
由于导入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);
}
}