码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis批量导入 ,出现异常全部不添加(回滚)

时间:2019-09-12 13:42:24      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:short   indexof   equals   input   sde   new   EDA   actor   mod   

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批量导入 ,出现异常全部不添加(回滚)

标签:short   indexof   equals   input   sde   new   EDA   actor   mod   

原文地址:https://www.cnblogs.com/lazyli/p/11511110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!