springboot+mybatis多数据源

首先,既然是多数据源,那么我们就先看下数据源怎么配置的:

javaconfig类似下面这样:

MapperScan注解常用配置如下:

basePackages:Base packages to scan for MyBatis interfaces,也就是mapper接口所在包名

annotationClass:This property specifies the annotation that the scanner will search for,

也就是只扫描指定包下的指定注解作为mapper,通常为org.apache.ibatis.annotations.Mapper

markerInterface:This property specifies the parent that the scanner will search for,只扫描指定包下指定父接口的子接口作为mapper

sqlSessionTemplateRef:指定这组mapper关联的sqlSessionTemplate

sqlSessionFactoryRef:指定这组mapper关联的sqlSessionFactory

那么,问题来了,annotationClass,markerInterface都配置了或者都不配置会怎样?在org.mybatis.spring.annotation.MapperScannerRegistrar.registerBeanDefinitions中调用的org.mybatis.spring.mapper.ClassPathMapperScanner.registerFilters()代码如下:

一幕了然,如果都配置了,最终的mapper会是两者匹配的合集;如果都不配置,那么,最终的mapper会是basePackages下所有任意接口。

 使用地方在org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.isCandidateComponent:

 还有一个问题,sqlSessionTemplateRef和sqlSessionFactoryRef同时都配置了会怎样?或者不配置呢?

通常,如果只有一个sqlSessionFactory时是不需要配置的,只有容器中有多个时才需要指定一个。

如果都配置了呢?请看下面分析:

org.mybatis.spring.mapper.ClassPathMapperScanner.processBeanDefinitions(Set<BeanDefinitionHolder>)中处理每一个之前扫描mapper生成的BeanDefinition时,会给每一个BeanDefinition设置sqlSessionFactory,如下:

 看到log没,很清楚:Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.

看完mapper的处理,再来看关联的sqlSessionFactory:

根据指定数据源类型利用org.springframework.boot.jdbc.DataSourceBuilder创建dataSource,目前主流的是使用阿里开源的Druid数据库连接池作为数据源:

sqlSessionFactory创建:

通过SqlSessionFactoryBean关联dataSource和MapperXML,再通过@MapperScan关联sqlSessionFactory和mapper接口

 

 至此,单个数据源创建算是完成了。如题,多数据源怎么办?

方法一,手动配置多个dataSource,并在@MapperScan关联不同的sqlSessionFactory和mapper接口。

方法二,动态数据源,继承org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource,重写determineTargetDataSource方法,从targetDataSources中获取对应数据源操作数据库,通常在前面业务代码根据具体怎样的情况选择怎样的dataSource,然后通过设置ThreadLocal变量,这里获取变量信息来返回对应数据源。切入业务逻辑可以通过aop切面从dao层方法名入手,也可以通过mybatis的拦截器获取sql信息和入参决定选择哪个数据源。

 PS:如果是读写分离,通常情况下主库读写权限,从库只读权限,事务DataSourceTransactionManager配置在主库的dataSource上,@Transactional会自动从配置事务的dataSource中获取连接。

原文地址:https://www.cnblogs.com/restart30/p/11613480.html