原文链接:mybatis-plus(insertBatchSomeColumn批量添加) – 编程屋
目录
1 前言
大家平时在做业务时肯定会遇到会向表中批量添加数据的方法,那么这种方法mybatis-plus给我们提供了吗?首先baseMapper中肯定没有提供,如下:只是添加单个实体的
但是IService貌似给我们提供了一个批量添加的方法:saveBatch(Collection<T> entityList)
那我们就拿这个方法来测试一下
@Test
public void testInsertMore(){
//批量添加
//INSERT INTO user ( id, name, age ) VALUES ( ?, ?, ? )
List<User> list = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
User user = new User();
user.setName("ybc"+i);
user.setAge(20+i);
list.add(user);
}
boolean b = userService.saveBatch(list);
System.out.println(b);
}
插入成功后:以下是打印出的sql语句
可以发现:虽然saveBatch(Collection<T> entityList)这个方法我们代码中只是一行代码,但是底层其实还是单条插入的。
但是这样批量插入的速度有时其实是很慢的,那么有没有真正的批量插入方法呢?其实mybatis-plus给我们预留了一个真正批量插入的扩展插件InsertBatchSomeColumn
2 搭建工程
1)创建springboot项目,引入如下相关依赖
<!--mybatis-plus启动器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.5.1</version>
</dependency>
2)编写sql注入器
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)注入插件
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
@Bean
public EasySqlInjector easySqlInjector() {
return new EasySqlInjector();
}
}
4)编写自己的mapper继承BaseMapper
public interface EasyBaseMapper<T> extends BaseMapper<T> {
/**
* 批量插入 仅适用于mysql
*
* @param entityList 实体列表
* @return 影响行数
*/
Integer insertBatchSomeColumn(Collection<T> entityList);
}
5)实体类的mapper继承自己编写的mapper
@Repository
public interface UserMapper<T> extends EasyBaseMapper<User> {
}
6)主启动类
@SpringBootApplication
@MapperScan("com.atguigu.mybatisplus.mapper")
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
以上只是部分内容,为了维护方便,文章已迁移到新地址:mybatis-plus(insertBatchSomeColumn批量添加) – 编程屋