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);
添加的時候使用這個,分批次導入,可以計入那行是錯誤的,返回;成功添加了多少行都可以處理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM