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);
添加的时候使用这个,分批次导入,可以计入那行是错误的,返回;成功添加了多少行都可以处理

猜你喜欢

转载自www.cnblogs.com/lazyli/p/11511110.html
今日推荐