最近改造老项目需要使用两个数据库,故而总结了一下mybatis的双数据源配置,学过mybatis的都知道mybatis其实就是封装了JDBC的框架,使用mybatis绕不开sqlSessionFactory的配置,那配置多个数据源的核心也是在于配置多个session工厂,用不同的工厂去操作不同的数据库就ok了,具体配置请参照下面配置文件说明,分为springboot和springmvc两种
springboot + mybatis
1、首先application.yml文件里面的datasource配置,这里就不写连接池的具体属性了
#主数据库
spring.datasource.primary.url=jdbc:mysql://localhost:3306/pa_db?useUnicode=true&characterEncoding=utf-8
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
#省略连接池配置
#从数据库
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/cas_user_db?useUnicode=true&characterEncoding=utf-8
spring.datasource.secondary.username=root
spring.datasource.secondary.password=root
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
2、接着就是核心的sqlSessionFactory配置
2.1、主数据源
basePackages
对应的是dao类放置地址,不同的数据源dao和mapper分开放
@Configuration
@MapperScan(basePackages = "com.xxxx.xxxx.dao", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDataSourceConfig {
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
// sqlSessionFactory配置
@Bean(name = "primarySqlSessionFactory")
@Primary /*此处必须在主数据库的数据源配置上加上@Primary*/
public SqlSessionFactory testSqlSessionFactory(@Qualifier("paDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
/*加载mybatis全局配置文件*/
bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mybatis-config.xml"));
/*加载所有的mapper.xml映射文件*/
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/*.xml"));
return bean.getObject();
}
// 事务配置
@Bean(name = "primaryTransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "paSqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2.2、 从数据源
@Configuration
@MapperScan(basePackages = "com.xxxx.xxxx.mapper2", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class SecondaryDataSource2Config {
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
/*加载mybatis全局配置文件*/
bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mybatis-config.xml"));
/*加载所有的mapper.xml映射文件*/
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/*.xml"));
return bean.getObject();
}
@Bean(name = "secondaryTransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "secondarySqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
基本上就这些,大家看看代码就懂了,其实就是将不同的数据库的mapper文件分开放置,然后配置sqlSessionFactory时去分开扫描就可以了,下面的springmvc其实也是一样的原理,只是将SQLSessionFactory的配置放在了配置文件中
springmvc + mybatis
1、数据源配置
springmvc是将session工厂放到配置文件中完成,与springboot原理是一样,然后写一个动态切换数据源的方法,用来切换不同的数据源,当然这种方式比较适合那种在老项目中间插入代码的方式,不需要频繁的切换数据源,反之建议使用aop的方式来配置,具体方法可以百度下,这里我就不写了
<!-- 主数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 省略其他连接池配置 -->
</bean>
<!-- 从数据源-->
<bean id="secondaryDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 省略其他连接池配置 -->
</bean>
<!-- 动态数据源配置,class对应的就是动态切换数据源的类 -->
<bean id="dynamicDataSource" class="com.thinkgem.jeesite.modules.dongbao.bug.support.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- 指定lookupKey和与之对应的数据源,这里的key可以自行定义,要切换数据库的时候以key为标识,不要写错 -->
<entry key="dataSource" value-ref="dataSource"></entry>
<entry key="secondaryDataSource" value-ref="secondaryDataSource"></entry>
</map>
</property>
<!-- 这里可以指定默认的数据源 -->
<property name="defaultTargetDataSource" ref="dataSource" />
</bean>
<!-- sqlSessionFactory配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dynamicDataSource"/>
<property name="typeAliasesPackage" value="com.thinkgem.jeesite"/>
<property name="typeAliasesSuperType" value="com.thinkgem.jeesite.common.persistence.BaseEntity"/>
<property name="mapperLocations" value="classpath:/mappings/**/*.xml"/>
<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
</bean>
2、数据源动态类
2.1、 获取数据源
这个地方对应的就是配置文件中的动态数据源
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// 从自定义的位置获取数据源标识
return DynamicDataSourceHolder.getDataSource();
}
}
2.2、切换数据源
public class DynamicDataSourceHolder {
/**
* 注意:数据源标识保存在线程变量中,避免多线程操作数据源时互相干扰
*/
private static final ThreadLocal<String> THREAD_DATA_SOURCE = new ThreadLocal<String>();
public static String getDataSource() {
return THREAD_DATA_SOURCE.get();
}
public static void setDataSource(String dataSource) {
THREAD_DATA_SOURCE.set(dataSource);
}
public static void clearDataSource() {
THREAD_DATA_SOURCE.remove();
}
}
3、使用方法
前文有指定默认数据源,默认情况下都会指向那个默认的,如果在请求某个接口时需要使用从数据源则手动切换
public List<JiraBug> issueByDay(@RequestBody JiraBugVO jiraBugVO) {
// 手动设置数据源
DynamicDataSourceHolder.setDataSource("secondaryDataSource");
logger.info("在controller中获取当前数据源" + DynamicDataSourceHolder.getDataSource());
List<JiraBug> mapList = bugJiraService.issueByCustomer(jiraBugVO);
return mapList;
}