• Mybatisplus真实高效批量插入附容错机制


    概要

    提示:mybatisplus自带真实批量插入

    在mybatisplus已知常用批量插入为继承Iservice里的saveBatch方法和saveOrUpdateBatch方法,
    进入源码可知,此两种方法的插入均为单条插入,如图:
    其中可看出
    其中可看出,实则调用的sql方法为:
    在这里插入图片描述
    则此sql插入效率跟单条插入无异,只是省了一些代码操作。

    优化

    此时我们可以自定义mybatisplus的SqlInjector
    具体操作为:

    class EasySqlInjector : MppSqlInjector() {
        override fun getMethodList(mapperClass: Class<*>?): MutableList<AbstractMethod> {
            val methodList = super.getMethodList(mapperClass)
            methodList.add(InsertBatchSomeColumn())
            return methodList
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    继承mybatisplus原先自带的sql方法,并加入**InsertBatchSomeColumn()方法,进入此方法源码查看,
    在这里插入图片描述
    它的实现方法相当于mybatisplus的
    **标签
    在这里插入图片描述

    技术细节

    这里我们要利用spring的IOC把它交给Spring管理:

    @Configuration
    class MyatisPlusConfiguration {
    
        @Bean
        fun mybatisPlusInterceptor(): MybatisPlusInterceptor {
            val interceptor = MybatisPlusInterceptor()
            //向Mybatis过滤器链中添加分页拦截器
            interceptor.addInnerInterceptor(PaginationInnerInterceptor(DbType.POSTGRE_SQL))
            //还可以添加i他的拦截器
            return interceptor
        }
        @Primary
        @Bean
        fun easySqlInjector() : EasySqlInjector{
            return EasySqlInjector()
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    后续的mapper直接继承BaseMapper然后添加此方法即可使用:

    interface FqMinMapper : MppBaseMapper<FqpfminDto> {
        fun insertBatchSomeColumn(entityList: List<FqpfminDto>): Int
    
    }
    
    • 1
    • 2
    • 3
    • 4

    提示:这里批量插入时,如果一个出错可能会整批插入失败
    这里最好给表定义一个规则,如主键重复时插入忽略异常抛出null,在insert时加IGNORE
    也需要注意各数据库对于批量插入字节的限制。

    小结

    此方法提高插入速度数据量越大越明显,当然如果此需求无法满足,也可重写mybatisplus的sql注入器源码,然后自己注入去实现需要的功能

  • 相关阅读:
    Security思想项目总结
    鸿蒙HarmonyOS实战-ArkTS语言基础类库(并发)
    Typescript-01
    二、Rocketmq-dashboard的web管理页面部署
    每次审查 OKR时,团队要讨论的12个启发性问题
    ChatGPT王炸升级
    APP采用原生开发还是混合开发好?
    OpenHarmony页面级UI状态存储:LocalStorage
    CentOs7 配置jar包开机自启动
    什么是代理模式,用 Python 如何实现 Proxy(代理 或 Surrogate)对象结构型模式?
  • 原文地址:https://blog.csdn.net/qq_37860381/article/details/130845480