mybatis批量导入 ,出现异常全部不添加(回滚)
Posted lazyli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis批量导入 ,出现异常全部不添加(回滚)相关的知识,希望对你有一定的参考价值。
public int importModel(MultipartFile file) throws Exception
String fileName = file.getOriginalFilename();
String suffxName = fileName.substring(fileName.lastIndexOf(".",fileName.length()) );
//System.out.println(fileName+",后缀名:"+suffxName);
String prefix=fileName.substring(fileName.lastIndexOf("."));
final File excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
//批量处理
SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
commericalModelMapper = session.getMapper(CommericalModelMapper.class);
// MultipartFile to File
file.transferTo(excelFile);
//判断excelp版本
Workbook workbook = null;
if(suffxName.equals(".xlsx"))
workbook = new XSSFWorkbook(new FileInputStream(excelFile));
else
workbook = new HSSFWorkbook(new FileInputStream(excelFile));
int count = 0;
if(workbook != null)
//获取excel中的数据,转换为实体类
Sheet sheet = workbook.getSheetAt(0);
List<CommericalModel> commericalModelList = CommericalModelResult.excelToModel(sheet);
int limitCount = 1000;
//进行批量添加操作(有一条不成功,全部回滚)
if(commericalModelList != null && commericalModelList.size() > 0)
for(int i = 0 ; i < commericalModelList.size();i++)
CommericalModel commericalModel = commericalModelList.get(i);
commericalModel.setCreateDate(new Date());
commericalModel.setUpdateDate(new Date());
commericalModel.setModelIsDelete((short)1);
commericalModelMapper.insert(commericalModel);
/*if(i != 0 && i%limitCount == 0)
//数量达到1000提交一次
session.commit();
*/
count++;
session.commit();
//删除临时文件
if(excelFile.exists())
excelFile.delete();
return count;
SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
commericalModelMapper = session.getMapper(CommericalModelMapper.class);
commericalModelMapper.insert(commericalModel);
添加的时候使用这个,分批次导入,可以计入那行是错误的,返回;成功添加了多少行都可以处理
以上是关于mybatis批量导入 ,出现异常全部不添加(回滚)的主要内容,如果未能解决你的问题,请参考以下文章
mybatis-plus解决 sqlserver批量插入list报错
mybatis-plus解决 sqlserver批量插入list报错
mybatis批量更新两种方式:1.修改值全部一样 2.修改每条记录值不一样