在实际开发中,批量插入是提高数据处理效率的常用手段。MyBatis-Plus 作为 MyBatis 的增强工具,提供了多种方式来实现批量插入。然而,默认的
saveBatch
方法在底层实际上是逐条插入,性能上并不理想。本文将详细介绍如何通过 MyBatis-Plus 实现真正高效的批量插入,包括手动拼接 SQL、使用IService
接口以及自定义insertBatchSomeColumn
方法,并提供性能优化建议。
文章目录
一、通过 XML 手动拼接 SQL 实现批量插入
优势
- 高效:一次性执行批量插入,减少数据库交互次数。
- 灵活:可以根据需要选择性插入部分字段,减少不必要的数据传输。
缺点
- 维护成本高:每个表都需要手动编写对应的 XML SQL。
- 不支持自动生成主键:如果表中有自增主键,需额外处理。
实现步骤
编写 Mapper XML 文件
以
history_summary
表为例,编写批量插入的 XML:<insert id="insertBatch" parameterType="java.util.List"> INSERT INTO history_summary (key_id, business_no, status, customer_id, instruction_id, customer_business_no, dept_id, doc_type_id, doc_page_no, document_version, result_mongo_doc_id, is_active, problem_status, tran_source, document_count_page, is_rush, is_deleted, document_tran_time, customer_tran_time, preprocess_recv_time, delete_time, create_time, complete_time, version, zip_name, document_no, new_task_type, handle_begin_time, handle_end_time, cost_seconds, char_num, ocr_result_mongo_id, reserve_text2, reserve_text3, reserve_text1, reserve_text4, reserve_text5, ocr_result_type, repeat_status, form_version, repetition_count) VALUES <foreach collection="list" item="item" separator=","> (#{item.keyId}, #{item.businessNo}, #{item.status}, #{item.customerId}, #{item.instructionId}, #{item.customerBusinessNo}, #{item.deptId}, #{item.docTypeId}, #{item.docPageNo}, #{item.documentVersion}, #{item.resultMongoDocId}, #{item.isActive}, #{item.problemStatus}, #{item.tranSource}, #{item.documentCountPage}, #{item.isRush}, #{item.isDeleted}, #{item.documentTranTime}, #{item.customerTranTime}, #{item.preprocessRecvTime}, #{item.deleteTime}, #{item.createTime}, #{item.completeTime}, #{item.version}, #{item.zipName}, #{item.documentNo}, #{item.newTaskType}, #{item.handleBeginTime}, #{item.handleEndTime}, #{item.costSeconds}, #{item.charNum}, #{item.ocrResultMongoId}, #{item.reserveText2}, #{item.reserveText3}, #{item.reserveText1}, #{item.reserveText4}, #{item.reserveText5}, #{item.ocrResultType}, #{item.repeatStatus}, #{item.formVersion}, #{item.repetitionCount}) </foreach> </insert>
在 Mapper 接口中定义批量插入方法
public interface historySummaryMapper extends BaseMapper<historySummary> { @Insert({ "<script>", "INSERT INTO history_summary ", "(key_id, business_no, status, customer_id, instruction_id, customer_business_no, dept_id, doc_type_id, doc_page_no, document_version, result_mongo_doc_id, is_active, problem_status, tran_source, document_count_page, is_rush, is_deleted, document_tran_time, customer_tran_time, preprocess_recv_time, delete_time, create_time, complete_time, version, zip_name, document_no, new_task_type, handle_begin_time, handle_end_time, cost_seconds, char_num, ocr_result_mongo_id, reserve_text2, reserve_text3, reserve_text1, reserve_text4, reserve_text5, ocr_result_type, repeat_status, form_version, repetition_count)", "VALUES ", "<foreach collection='list' item='item' index='index' separator=','>", "(#{item.keyId}, #{item.businessNo}, #{item.status}, #{item.customerId}, #{item.instructionId}, #{item.customerBusinessNo}, #{item.deptId}, #{item.docTypeId}, #{item.docPageNo}, #{item.documentVersion}, #{item.resultMongoDocId}, #{item.isActive}, #{item.problemStatus}, #{item.tranSource}, #{item.documentCountPage}, #{item.isRush}, #{item.isDeleted}, #{item.documentTranTime}, #{item.customerTranTime}, #{item.preprocessRecvTime}, #{item.deleteTime}, #{item.createTime}, #{item.completeTime}, #{item.version}, #{item.zipName}, #{item.documentNo}, #{item.newTaskType}, #{item.handleBeginTime}, #{item.handleEndTime}, #{item.costSeconds}, #{item.charNum}, #{item.ocrResultMongoId}, #{item.reserveText2}, #{item.reserveText3}, #{item.reserveText1}, #{item.reserveText4}, #{item.reserveText5}, #{item.ocrResultType}, #{item.repeatStatus}, #{item.formVersion}, #{item.repetitionCount})", "</foreach>", "</script>" }) int insertBatch(@Param("list") List<historySummary> list); }
在 Service 层调用批量插入方法
@Service public class historySummaryServiceImpl extends ServiceImpl<historySummaryMapper, historySummary> implements IhistorySummaryService { @Autowired private historySummaryMapper mapper; @Transactional(rollbackFor = Exception.class) public boolean batchInsert(List<historySummary> list) { int result = mapper.insertBatch(list); return result > 0; } }
使用示例
@RestController @RequestMapping("/api/business") public class BusinessController { @Autowired private IhistorySummaryService service; @PostMapping("/batchInsert") public ResponseEntity<String> batchInsert(@RequestBody List<historySummary> list) { boolean success = service.batchInsert(list); if (success) { return ResponseEntity.ok("批量插入成功"); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("批量插入失败"); } } }
看到这里应该头皮发麻了吧。这也是我为什么想分享这篇文章的原因!!!
涉及到多字段批量插入,还是推荐下面的方法。
二、使用 MyBatis-Plus IService
接口的 saveBatch
方法
MyBatis-Plus 提供的 saveBatch
方法简化了批量插入的操作,但其底层实际上是逐条插入,因此在处理大量数据时性能不佳。
优势
- 简便易用:无需手动编写 SQL,直接调用接口方法即可。
- 自动事务管理:内置事务支持,确保数据一致性。
缺点
- 性能有限:底层逐条插入,面对大数据量时效率较低。
- 批量大小受限:默认批量大小可能不适用于所有场景,需要手动调整。
提升性能的方法
配置数据库连接参数
在数据库的连接 URL 中添加
rewriteBatchedStatements=true
,启用批量重写功能,提升批量插入性能。spring.datasource.url=jdbc:mysql://localhost:3306/your_database?rewriteBatchedStatements=true
调整批量大小
在调用
saveBatch
方法时,合理设置批量大小(如 1000 条一批),以平衡性能和资源消耗。@Transactional(rollbackFor = {Exception.class}) public boolean saveBatch(Collection<T> entityList, int batchSize) { String sqlStatement = this.getSqlStatement(SqlMethod.INSERT_ONE); return this.executeBatch(entityList, batchSize, (sqlSession, entity) -> { sqlSession.insert(sqlStatement, entity); }); }
三、insertBatchSomeColumn
方法实现批量插入
为了实现真正高效的批量插入,可以使用 insertBatchSomeColumn
方法,实现一次性批量插入。
优势
- 高效:一次性执行批量插入,减少数据库交互次数。
- 灵活:可选择性插入部分字段,优化数据传输。(通过实体类属性)
实现步骤
1. 自定义SQL注入器实现DefaultSqlInjector,添加InsertBatchSomeColumn方法
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
return methodList;
}
}
2. 将MySqlInjector注入到Bean中
@Configuration
public class MyBatisConfig {
@Bean
public MySqlInjector sqlInjector() {
return new MySqlInjector();
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
3. 继承Mybatis-plus的BaseMapper,添加插入方法
public interface MyBaseMapper<T> extends BaseMapper<T> {
int insertBatchSomeColumn(Collection<T> entityList);
}
@Mapper
public interface WorkingBusinessHistoryMapper extends MyBaseMapper<BusinessHistory> {
}
注意事项
- 批量大小:根据数据库和应用的性能,合理设置批量插入的大小,避免单次插入过多数据导致内存溢出或数据库压力过大。
- 事务管理:确保批量操作在事务中执行,以保证数据的一致性和完整性。
- 错误处理:在批量操作中,如果某条记录插入失败,需要有相应的机制进行回滚或记录失败信息。
四、性能优化建议
为了进一步提升批量插入的性能,可以采取以下优化措施:
1. 开启批量重写功能
在数据库的连接 URL 中添加 rewriteBatchedStatements=true
,以优化批量插入的性能。
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?rewriteBatchedStatements=true
2. 合理设置批量大小
根据具体业务场景和数据库性能,调整批量大小(如 1000 条一批),避免单次插入过多数据。
int batchSize = 1000;
for (int i = 0; i < list.size(); i += batchSize) {
List<historySummary> batchList = list.subList(i, Math.min(i + batchSize, list.size()));
mapper.insertBatchSomeColumn(batchList);
}
3. 使用事务管理
确保批量操作在事务中执行,避免部分插入成功导致数据不一致。
@Transactional(rollbackFor = Exception.class)
public boolean batchInsert(List<historySummary> list) {
int result = mapper.insertBatchSomeColumn(list);
return result > 0;
}
4. 索引优化
对插入频繁的表,合理设计索引,避免过多不必要的索引影响插入性能。尽量减少在批量插入时的索引数量,插入完成后再创建必要的索引。
5. 禁用自动提交
在批量插入过程中,禁用自动提交,减少事务提交的次数,提高性能。
jdbcTemplate.execute((ConnectionCallback<Void>) connection -> {
connection.setAutoCommit(false);
// 执行批量插入操作
connection.commit();
return null;
});