前言
這次使用到多數據源的原因是因爲重構一個項目,舊數據又需要遷移到新數據庫,數據庫表設計有差異,所以需要編寫程序進行遷移。
實現
目錄結構
application.yml
server:
port: 8080
spring:
profiles:
active: dev
application:
name: case-multi-dataSource
datasource:
table1:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/table1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
initialSize: 5
minIdle: 5
maxActive: 50
maxWait: 10000
timeBetweenEvictionRunsMillis: 10000
minEvictableIdleTimeMillis: 50000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
filters: stat,wall,log4j
table2:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/table2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
initialSize: 5
minIdle: 5
maxActive: 50
maxWait: 10000
timeBetweenEvictionRunsMillis: 10000
minEvictableIdleTimeMillis: 50000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
filters: stat,wall,log4j
配置兩個 DataSourceConfig
package com.example.multi.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
//basePackages 對應dao目錄
@MapperScan(basePackages = "com.example.utils.dao.table1.**", sqlSessionTemplateRef = "table1SqlSessionTemplate")
public class DataSource1Config {
@Bean(name = "table1DataSource")
//prefix 對應yml中數據庫配置信息
@ConfigurationProperties(prefix = "spring.datasource.table1")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "table1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("table1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// 如果有用到mybatis-config.xml配置,就需要配置一下兩行代碼,否則可以不用
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
// 配置mapper xml文件位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/table1/*.xml"));
return bean.getObject();
}
@Bean(name = "table1TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("table1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "table1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("table1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
package com.example.multi.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
//basePackages 對應dao目錄
@MapperScan(basePackages = "com.example.utils.dao.table1.**", sqlSessionTemplateRef = "table2SqlSessionTemplate")
public class DataSource2Config {
@Bean(name = "table2DataSource")
//prefix 對應yml中數據庫配置信息
@ConfigurationProperties(prefix = "spring.datasource.table2")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "table2SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("table2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// 如果有用到mybatis-config.xml配置,就需要配置一下兩行代碼,否則可以不用
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
// 配置mapper xml文件位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/table2/*.xml"));
return bean.getObject();
}
@Bean(name = "table2TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("table2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "table2SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("table2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
主要部分已經完成,其他操作只要在dao和mapper中兩個不同的實現即可
事務處理
單數據源事務
//此處transactionManager 指向config中的Bean
@Transactional(transactionManager = "table1TransactionManager")
public void insert() {
table1Dao.insertTable1();
}
注意:以下操作兩個數據源,第一個成功插入數據庫,第二個失敗進行回滾
//此處transactionManager 指向config中的Bean
@Transactional(transactionManager = "table1TransactionManager")
public void insert() {
table1Dao.insertTable1();
table2Dao.insertTable2();
}