架构:springboot2.6.7 + mariadb10.x + mybatisplus2.3.x

方案一,使用原生方法(saveBatch())【性能一般,无须配置】

使用原生方法插入,每次最多只能添加1000条数据,若有一次插入1000条以上需求,需另辟蹊径。

原生批量插入样例如下:

package com.softscenene.server.drugPurchase.domain.hospLedger.flowMeter;

@Slf4j
@Service
public class FlowMeterService extends BasicService<FlowMeterMapper, FlowMeter> {

    @Resource
    private FlowMeterMapper flowMeterMapper;

    public boolean batchSave(ArrayList<FlowMeter> arrayList){
        return batchSave(arrayList);
    }
}

方案二,基于mybatisPlus自定义SQL语句(支持一千条以上,xml文件)

方案三,基于mybatisPlus的批量插入(性能最优,但需配置)。

前两种方法配置简单,但面对数十万数据时,性能低下,此处详细介绍第三中方案。

@Mapper
public interface FlowMeterMapper extends BaseMapper<FlowMeter> {
    /**
     * 批量插入 仅适用于mysql
     * @param entityList 实体列表
     * @return 影响行数
     */
    Integer insertBatchSomeColumn(Collection<FlowMeter> entityList);
}
@Configuration
@EnableTransactionManagement //开启mybatis事物管理
public class MPConfiguration {
    @Bean
    @Primary//批量插入配置
    public EasySqlInjector easySqlInjector() {
        return new EasySqlInjector();
    }
}
public class EasySqlInjector extends DefaultSqlInjector {
    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
        List<AbstractMethod> methodList=super.getMethodList(mapperClass, tableInfo);
        methodList.add(new InsertBatchSomeColumn());//添加批量插入方法
        return methodList;
    }
}
    /** @日期: 2022-03-25       @作者: 离染
     *  @描述: 批量保存流水*/
    @SneakyThrows(Exception.class)
    @Transactional
    public void asyncSaveFlowMeter(List<FlowMeter> flowMeters,String batchSign) {
        log.info("日金额——异步保存流水——将保存流水条数:{},批次标记:{}",flowMeters.size(),batchSign);
        Integer saveCount=flowMeterMapper.insertBatchSomeColumn(flowMeters);
        if(saveCount<0){
            log.error("日金额——异步保存流水——保存失败,失败数据为:{},批次标记:{}",flowMeters,batchSign);
            return;
        }
        log.info("日金额——异步保存流水——保存成功,成功条数:{},批次标记:{}",saveCount,batchSign);
        flowMeters.clear();
    }

注意:第三种方案只支持mysql,且在连接时,需添加批量写入参数,完整mysql连接如下【jdbc:mysql://127.0.0.1:3306/drug?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true&rewriteBatchedStatements=true】

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐