mybaties-plus 并没有封装真正意义上的批量操作方法,自带的saveBatch()方法底层也是for操作,但是给我们留了自定义方法的空间:
/**
* SQL 默认注入器 添加批量插入方法
* @author lijin
* @since 2018-04-10
*/
public class SpiceSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
// 注意:此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自带方法
List<AbstractMethod> methodList = super.getMethodList(mapperClass,tableInfo);
// 注入InsertBatchSomeColumn
// 在!t.isLogicDelete()表示不要逻辑删除字段,!"update_time".equals(t.getColumn())表示不要字段名为 update_time 的字段
methodList.add(new InsertBatchSomeColumn(t -> !t.isLogicDelete() && !"creat_time".equals(t.getColumn()) && !"update_time".equals(t.getColumn())));
return methodList;
}
}
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
@Bean
public SpiceSqlInjector easySqlInjector () {
return new SpiceSqlInjector();
}
}
public interface BaseDaoMapper<T> extends BaseMapper<T> {
/**
* 批量插入 仅适用于mysql
* @param entityList 实体列表
* @return 影响行数
*/
Integer insertBatchSomeColumn(Collection<T> entityList);
}
值得注意的是方法名字必须为insertBatchSomeColumn,因为在mybaties的模板里面已经指定了名称
结果:
可以看到执行的sql只有一句,避免了循环操作,提高了效率