网上数据源动态切换的文章大多千篇一律而且还是各种地方都有坑,博主在这里被坑惨了。。。
多数据源动态切换需要自定义实例化sqlSessionFactoryBean
然后自定义的需要手动设置setMapperLocations、setTypeAliasesPackage不然执行sql时会报
org.apache.ibatis.binding.BindingException:
* Invalid bound statement (not found)…
原因以及解决方案如下:
@Bean
@ConfigurationProperties(prefix = "mybatis")
public MybatisSqlSessionFactoryBean sqlSessionFactoryBean() {
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
/**
* 这里在applications.properties里面配置了
* mybatis-plus.type-aliases-package=com.jwt.springboot.dao
* mybatis-plus.mapper-locations=classpath:mapper/*Mapper.xml
* 但多数据源情况下执行sql总会报:org.apache.ibatis.binding.BindingException:
* Invalid bound statement (not found)........
* 原因是 this.mapperLocations 为null
*
* 注!!!!这里有大坑, 因为这里是自定义的sqlSessionFactoryBean,所以导致
* 没有启动时没有通过org.mybatis.spring.boot.autoconfigure.MybatisPlusAutoConfiguration
* 类的sqlSessionFactory(DataSource dataSource)方法自动装配sqlSessionFactoryBean
* 自定义的sqlSessionFactoryBean所以也没设置mapperLocations
* 故自定义实例化sqlSessionFactoryBean这里需要手动设置mapperLocations
* 可参考:https://developer.aliyun.com/article/754124
*/
if (!ObjectUtils.isEmpty(this.mybatisPlusProperties.resolveMapperLocations())) {
sqlSessionFactoryBean.setMapperLocations(this.mybatisPlusProperties.resolveMapperLocations());
}
if (this.mybatisPlusProperties.getTypeAliasesPackage() != null) {
sqlSessionFactoryBean.setTypeAliasesPackage(this.mybatisPlusProperties.getTypeAliasesPackage());
}
sqlSessionFactoryBean.setDataSource(dynamicDataSource());
return sqlSessionFactoryBean;
}