mybatis-plus实现批量插入
前言
mybatis-plus自带的saveBatch 性能并不能满足我们的需求,故有了insertBatchSomeColumn的扩展。但是扩展后出现了Invalid bound statement (not found): insertBatchSomeColumn的报错,网上却始终搜不到正确的解决办法,故这里记录一下,需要看解决办法的可以直接拉到最后。
注:这里我使用的mybatis-plus是3.1.2版本的,不同版本可能有所差别
引入pom依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.1.2</version>
</dependency>
编写sql注入器
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.injector.methods.additional.InsertBatchSomeColumn;
import java.util.List;
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
return methodList;
}
}
注入bean
@Bean
public MySqlInjector sqlInjector() {
return new MySqlInjector();
}
使用方式
方式一、直接在Mapper文件中添加该方法
Integer insertBatchSomeColumn(Collection<T> entityList);
例:
public interface planInfoMapper extends BaseMapper<PlanInfo> {
int insertBatchSomeColumn(List<PlanInfo> entityList);
}
方式二、编写自己的mapper继承BaseMapper,并在其他继承BaseMapper的类上改为继承自己的mapper
public interface MyBaseMapper<T> extends BaseMapper<T> {
/**
* 批量插入 仅适用于mysql
*
* @param entityList 实体列表
* @return 影响行数
*/
Integer insertBatchSomeColumn(Collection<T> entityList);
}
public interface ImbPtePlanInfoMapper extends MyBaseMapper<PlanInfo> {
}
大部分博客到这里,基本就完结撒花了,但是实际上,某些情况我们直接调用该方法,是没办法用的。
报错解决
在实际使用过程中,可能会出现如下报错:
org.apache.ibatis.binding.BindingException:
Invalid bound statement (not found): xxx.xxx.xxx.insertBatchSomeColumn
这个时候,就可能是我们使用了自己的SqlSessionFactory
那么就需要手动设置SqlInjector
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setCallSettersOnNulls(true);
//禁用mybatis 一级缓存
configuration.setLocalCacheScope(LocalCacheScope.STATEMENT);
bean.setConfiguration(configuration);
bean.setMapperLocations(resolveMapperLocations());
Interceptor[] plugins = {paginationInterceptor};
bean.setPlugins(plugins);
//关键点,请注意这里
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setSqlInjector(new MySqlInjector());
bean.setGlobalConfig(globalConfig);
至此,问题解决!