mybatis-plus真正实现批量插入(只针对MySQL数据库)

说明

  • mybatis-plus提供的saveBatch方法并不能真正实现批量插入,底层原理是for循环单条插入。所以要想真正实现批量得自己写批量插入方法。
  • 如下

步骤一

导入mybatis-plus依赖

        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>

步骤二

编写插入方法

@Component
public class InsertBatchSqlInjector extends DefaultSqlInjector {
    
    

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
    
    
        // super.getMethodList() 保留 Mybatis Plus 自带的方法
        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
        // 添加自定义方法:批量插入,方法名为 insertBatchSomeColumn
        methodList.add(new InsertBatchSomeColumn());
        return methodList;
    }
}

步骤三

添加mybatis配置类

@Configuration
// 扫描mapper包
@MapperScan("com.example.java.mapper")
public class MybatisPlusConfig {
    
    
    /**
     * 自定义批量插入 SQL 注入器
     */
    @Bean
    public InsertBatchSqlInjector insertBatchSqlInjector() {
    
    
        return new InsertBatchSqlInjector();
    }
}

步骤四

继承BaseMapper类,编写自己的MyBaseMapper

public interface MyBaseMapper<T> extends BaseMapper<T> {
    
    

    int insertBatchSomeColumn(@Param("list") List<T> batchList);

}

步骤五

使用

@Service
public class UserServiceImpl implements UserService {
    
    

    @Resource
    private UserMapper userMapper;

    @Override
    public int insertBatch(List<User> records) {
    
    
        return userMapper.insertBatchSomeColumn(user);
    }
}

以上就是实现批量插入的全部内容啦,希望能帮到您!如果觉得不错的话,欢迎收藏。

猜你喜欢

转载自blog.csdn.net/qq_43813351/article/details/129583020