MybatisPlus实现真正批量插入的详细步骤

 更新时间:2024年10月08日 10:10:23   作者:总是学不会.  
在数据库操作中,批量插入是提升效率的重要手段,MyBatis-Plus提供了多种批量插入方法,但默认的saveBatch方法效率并不高,文章介绍了通过手动拼接SQL、使用IService接口以及自定义insertBatchSomeColumn方法进行优化,以实现更高效的批量插入,并给出了性能优化建议

在实际开发中,批量插入是提高数据处理效率的常用手段。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;
});

参考

MybatisPlus自定义insertBatchSomeColumn实现真正批量插入 - CSDN博客

MybatisPlus如何实现insertBatchSomeColumn进行批量增加 - 亿速云

MyBatis-Plus 官方文档

MySQL Connector/J Documentation

到此这篇关于MybatisPlus实现真正批量插入的文章就介绍到这了,更多相关MybatisPlus批量插入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java使用JavaMail API发送和接收邮件的代码示例

    Java使用JavaMail API发送和接收邮件的代码示例

    JavaMail是Oracle甲骨文开发的Java邮件类API,支持多种邮件协议,这里我们就来看一下Java使用JavaMail API发送和接收邮件的代码示例
    2016-06-06
  • 关于springboot2整合lettuce启动卡住问题的解决方法

    关于springboot2整合lettuce启动卡住问题的解决方法

    Lettuce和Jedis的都是连接Redis Server的客户端程序,下面这篇文章主要给大家介绍了关于springboot2整合lettuce启动卡住问题的解决方法,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2021-12-12
  • Java 二叉树遍历特别篇之Morris遍历

    Java 二叉树遍历特别篇之Morris遍历

    二叉树的遍历(traversing binary tree)是指从根结点出发,按照某种次序依次访问二叉树中所有的结点,使得每个结点被访问依次且仅被访问一次。四种遍历方式分别为:先序遍历、中序遍历、后序遍历、层序遍历
    2021-11-11
  • java必懂的冷知识点之Base64加密与解密

    java必懂的冷知识点之Base64加密与解密

    这篇文章主要介绍了java必懂的冷知识点之Base64加密与解密的相关资料,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • 使用Spring实现@Value注入静态字段

    使用Spring实现@Value注入静态字段

    这篇文章主要介绍了使用Spring实现@Value注入静态字段方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • Java排序的那些事之sort方法的使用详解

    Java排序的那些事之sort方法的使用详解

    sort方法用于对数组的元素进行排序。排序顺序可以是字母或数字,并按升序或降序。默认排序顺序为按字母升序,当数字是按字母顺序排列时"40"将排在"5"前面。使用数字排序,你必须通过一个函数作为参数来调用。这些说起来可能很难理解,你可以通过本篇文章进一步了解它
    2021-09-09
  • Java FTP协议实现文件下载功能

    Java FTP协议实现文件下载功能

    FTP(File Transfer Protocol)就是文件传输协议。通过FTP客户端从远程FTP服务器上拷贝文件到本地计算机称为下载,将本地计算机上的文件复制到远程FTP服务器上称为上传,上传和下载是FTP最常用的两个功能
    2022-11-11
  • 一文详解Spring中的HttpMessageNotReadableException异常处理

    一文详解Spring中的HttpMessageNotReadableException异常处理

    这篇文章主要为大家详细介绍了Spring中的HttpMessageNotReadableException异常,分析其产生的原因并通过实际代码示例展示如何有效地捕获和处理这一异常,感兴趣的可以了解下
    2025-02-02
  • shiro拦截认证的全过程记录

    shiro拦截认证的全过程记录

    Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理,下面这篇文章主要给大家介绍了关于shiro拦截认证的相关资料,需要的朋友可以参考下
    2021-11-11
  • Spring MVC 启动过程源码分析详解

    Spring MVC 启动过程源码分析详解

    这篇文章主要介绍了Spring MVC 启动过程源码分析详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07

最新评论