记一下Mybatis-plus实现批量插入数据库

MybatisPlus实现批量插入

1.背景

mybatis-plus 新添加了一个sql注入器,通过sql注入器可以实现批量新增,批量新增修改功能。一次注入,随时使用,使用极其方便。
缺点就是项目启动时候,会进行sql注入器注册,稍微影响启动速度。

step1:添加依赖

添加这个依赖可能会造成别的依赖失效,比如,分页插件以及逻辑删除插件这个是因为这个依赖的版本较高,已经不需要配置逻辑删除插件了,可以直接删掉,功能不会受到影响


<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-extensionartifactId>
    <version>3.4.3.4version>
dependency>
step2:创建injector包,并在此包下创建类继承默认的注入方法
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
import java.util.List;

public class EasySqlInjector extends DefaultSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        methodList.add(new InsertBatchSomeColumn());
        return methodList;
    }
}
step4:在mybatisconfig配置文件中创建类注入bean
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor page = new PaginationInterceptor();
//        page.setDialectType("mysql");
//        return new PaginationInterceptor();
//    }

    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
//如果mybaitsplus的版本比较新的话,逻辑删除的插件是可以省略的

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MyMetaObjectHandler();
    }

    @Bean
    public GlobalConfig globalConfiguration() {
        GlobalConfig conf = new GlobalConfig();
        // 自定义的注入需要在这里进行配置
        conf.setSqlInjector(easySqlInjector());
        return conf;
    }

    @Bean
    public EasySqlInjector easySqlInjector() {
        return new EasySqlInjector();
    }
step5:扩展自带的baseMapper

在mapper包下新建EasyBaseMapper接口,扩展自带的baseMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;

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

    /**
     * 批量插入 仅适用于mysql,若改变数据库需要修改配置类中有关数据库类型的配置
     * @param entityList 实体列表
     * @return 影响行数
     */
    Integer insertBatchSomeColumn(List<T> entityList);
}
step6:业务实现

mapper文件夹下创建持久化类

@Mapper
public interface XXXMapper extends EasyBaseMapper<需要操作的实体类> {
}

最后就可以直接在service层注Mapper对象,进行批量插入。

你可能感兴趣的:(数据库,java,mybatis)