Mybatis-plus 批量插入insertBatchSomeColumn的使用

发布时间 2023-11-09 14:58:44作者: Ritchie王则钰

Mybatis-plus 的 service 层

IService 接口下的 saveBatch 批量插入方法不够高效

Mybatis-plus 的 mapper 层有个选装件

insertBatchSomeColumn

1,新增一个类

此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法

public class MySqlInjector extends DefaultSqlInjector { 
    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        methodList.add(new InsertBatchSomeColumn()); //添加批量插入方法
        return methodList;
    }
}

2,在核心配置类 MybatisPlusConfig 中注入Bean

@Configuration
public class MybatisPlusConfig {
    /**
     * 其他Bean
     */
    // ...

    
    @Bean
    public EasySqlInjector sqlInjector() {
        return new EasySqlInjector();
    }
}

3,在xxxMapper层加一个

返回受影响行数,只测试过MySQL

int insertBatchSomeColumn(List<T> entityList);

4,在类中直接调用,不用写xml文件

List<TXxx> xxxList = 获取xxxList的方法;
//xxxService.saveBatch(xxxList); // 伪批量插入
xxxMapper.insertBatchSomeColumn(xxxList); // 真批量插入