问题如上,对测试环境做了mysql读写分离的改造,增加了mybatis-plus多数据配置,其他情况一切顺利,但在执行saveBatch方法的时候会提示Resource must not be null。
下图中的sqlSessionFactory()方法中最开始用的是SqlSessionFactoryBean,这个是spring集成mybatis中提供的,然后再测试环境中执行saveBatch就一直报Resource must not be null错误,后来经过debug分析,发现需要使用mybatis-plus自带的MybatisSqlSessionFactoryBean操作可以解决。简单分析一下就是,mybatis-plus自己封装的MybatisSqlSessionFactoryBean多了一个GlobalConfig属性,在执行saveBatch方法的时候会去通过操作GlobalConfig,生成sqlSessionFactory,而mybatis中的SqlSessionFactoryBean是不带这个属性的,所以如果通过SqlSessionFactoryBean去生成SqlSessionFactory它的globalConfig就为空,在后续的操作上直接抛出了异常。
总结:Mybatis-plus集成多数据源的情况下,建议使用MybatisSqlSessionFactoryBean去生成SqlSessionFactory,可以减少一些不必要的麻烦
mybatis-plus的配置类
@Configuration
@MapperScan("com.asurplus.*.mapper")
public class MybatisPlusConfig {
@Resource(name = "targetDataSource")
private DataSource dataSource;
/**
* 配置SqlSessionFactory
* @return
* @throws Exception
*/
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
// SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
//使用mybatis-plus自带的MybatisSqlSessionFactoryBean
MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml"));
factoryBean.setTypeAliasesPackage("com.asurplus.*.entity");
MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
mybatisConfiguration.setMapUnderscoreToCamelCase(true);
mybatisConfiguration.setCacheEnabled(false);
mybatisConfiguration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
factoryBean.setConfiguration(mybatisConfiguration);
factoryBean.setPlugins(paginationInterceptor());
return factoryBean.getObject();
}
/**
* 配置事务管理
* @return
*/
@Bean
public PlatformTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setLimit(5000L);
return paginationInterceptor;
}
}