1、安装依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.5.3.2</version>
</dependency>
版本与mybatis-plus一致
2、编写sql注入器
package com.example.answer_system.config;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
import java.util.List;
public class EasySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
// 注意:此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自带方法
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
return methodList;
}
}
3、注入插件
package com.example.answer_system.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
//插件,用于批量插入真正的
@Bean
public EasySqlInjector easySqlInjector() {
return new EasySqlInjector();
}
}
4、编写自己的mapper继承BaseMapper
package com.example.answer_system.base;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.Collection;
public interface BasePlusMapper <T> extends BaseMapper<T> {
//真正的批量插入
Integer insertBatchSomeColumn(Collection<T> entityList);
}
5、代码中使用,实体类的mapper继承自己编写的BasePlusMapper
在代码中使用时
baseMapper.insertBatchSomeColumn(list);则可实现真正的批量插入