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

    public void saveTemp(List<AddressBookDepartmentAllSyncTemp> allSyncTemps) {
        baseMapper.deleteTempTable();
        if (allSyncTemps.size() <= batchUpdateSize) {
            baseMapper.insertBatch(allSyncTemps);
        } else {
            SqlSession sqlSession = null;
            try {
                sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
                List<AddressBookDepartmentAllSyncTemp> 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 id="insertBatch" >
        insert into address_book_department_all_sync_temp (`id`,`data`) values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.id},#{item.data})
        </foreach>
    </insert>

 

Logo

永洪科技,致力于打造全球领先的数据技术厂商,具备从数据应用方案咨询、BI、AIGC智能分析、数字孪生、数据资产、数据治理、数据实施的端到端大数据价值服务能力。

更多推荐