mybatis 大数据分批提交更新

在使用mybatis进行数据批量新增的时候,有时候数据过大时需要进行分批处理。这个时候就需要一些特殊的处理了,不多说,直接上代码

    public void saveTemp(List allSyncTemps) {
        baseMapper.deleteTempTable();
        if (allSyncTemps.size() <= batchUpdateSize) {
            baseMapper.insertBatch(allSyncTemps);
        } else {
            SqlSession sqlSession = null;
            try {
                sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
                List temps = new ArrayList<>();

                for (int index = 0,len = allSyncTemps.size() ; index < len; index ++) {
                    if(!ObjectUtils.isEmpty(allSyncTemps.get(index))){
                        temps.add(allSyncTemps.get(index));
                    }
                    if(index != 0 && index % batchUpdateSize == 0 && !ObjectUtils.isEmpty(temps)){
                        baseMapper.insertBatch(temps);
                        sqlSession.commit();
                        temps.clear();
                    }else if(index == len-1 && !ObjectUtils.isEmpty(temps)){
                        baseMapper.insertBatch(temps);
                        sqlSession.commit();
                        temps.clear();
                    }
                }
            }catch (Exception e){
                sqlSession.rollback();
                throw new RuntimeException("保存部门临时数据异常",e);
            }finally {
                if (sqlSession != null) {
                    sqlSession.close();
                }

            }}
        }

mapp.xml

   
        insert into address_book_department_all_sync_temp (`id`,`data`) values
        
            (#{item.id},#{item.data})
        
    

 

你可能感兴趣的:(JAVA,springboot,Java,技术杂谈)