架构: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方案二,基于mybatisPlus自定义SQL语句(支持一千条以上,xml文件) 方案三,基于mybatisPlus的批量插入(性能最优,但需配置)。{ @Resource private FlowMeterMapper flowMeterMapper; public boolean batchSave(ArrayList arrayList){ return batchSave(arrayList); } }
前两种方法配置简单,但面对数十万数据时,性能低下,此处详细介绍第三中方案。
@Mapper public interface FlowMeterMapper extends BaseMapper{ Integer insertBatchSomeColumn(Collection entityList); }
@Configuration
@EnableTransactionManagement //开启mybatis事物管理
public class MPConfiguration {
@Bean
@Primary//批量插入配置
public EasySqlInjector easySqlInjector() {
return new EasySqlInjector();
}
}
public class EasySqlInjector extends DefaultSqlInjector {
@Override
public List getMethodList(Class> mapperClass, TableInfo tableInfo) {
List methodList=super.getMethodList(mapperClass, tableInfo);
methodList.add(new InsertBatchSomeColumn());//添加批量插入方法
return methodList;
}
}
@SneakyThrows(Exception.class)
@Transactional
public void asyncSaveFlowMeter(List 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】



