在實際的項目開發過程當中咱們會常常遇到一個項目操做多個數據庫的問題,也就是多數據源的問題。那麼本篇文章將經過一個具體的例子來說解如何在SpringBoot+Mybatis+Druid+MySQL項目中實現多數據源的配置。java
一個springboot項目,能夠去官網快速生成一個,若是你不是很清楚怎麼生成的話,能夠看我以前的文章。
一個可用的MySQL數據庫。mysql
在本例中咱們將會新建兩個數據庫(dbone和dbtwo),其中dbone中擁有一張city表,dbtwo中包含一張user表。git
-- 建立數據庫
CREATE DATABASE dbone;
CREATE DATABASE dbtwo;
複製代碼
-- 在dbone中新建city表
USE dbone;
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '城市編號',
`province_id` int(10) unsigned NOT NULL COMMENT '省份編號',
`city_name` varchar(25) DEFAULT NULL COMMENT '城市名稱',
`description` varchar(25) DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT city VALUES (1 ,1,'上海市','直轄市');
複製代碼
-- 初始化dbtwo的表
USE dbtwo;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '用戶編號',
`user_name` varchar(25) DEFAULT NULL COMMENT '用戶名稱',
`description` varchar(25) DEFAULT NULL COMMENT '描述',
`city_id` int(11) DEFAULT NULL COMMENT '城市id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT user VALUES (1 ,'名字想好沒。', '我的主頁:https://itweknow.cn', 1);
複製代碼
在準備階段咱們就已經生成了一個SpringBoot的一個基礎的Web項目,前面也提到過咱們的例子使用的技術棧是SpringBoot+MySQL+MyBatis+Druid,在SpringBoot的Web項目基礎的依賴的基礎上咱們會增長mybatis、druid以及MySQL鏈接驅動這三個依賴,咱們只須要在項目的pom.xml中添加以下內容便可。 pom.xmlgithub
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--鏈接驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
複製代碼
## dbone 數據源配置
dbone.druid.datasource.url=jdbc:mysql://localhost:3306/dbone?serverTimezone=GMT%2B8
dbone.druid.datasource.username=root
dbone.druid.datasource.password=123456
dbone.datasource.driverClassName=com.mysql.jdbc.Driver
## dbtwo 數據源配置
dbtwo.druid.datasource.url=jdbc:mysql://localhost:3306/dbtwo?serverTimezone=GMT%2B8
dbtwo.druid.datasource.username=root
dbtwo.druid.datasource.password=123456
dbtwo.datasource.driverClassName=com.mysql.jdbc.Driver
複製代碼
DruidDataSourceProperties
咱們抽象了一個類來存儲建立一個數據源所須要的屬性,每一個數據源都有一個本身Properties類繼承自DruidDataSourceProperties,並利用@ConfigurationProperties註解來從配置文件中讀取各個配置項的值。因爲文章篇幅的緣由這裏就不貼代碼了,須要的話能夠在源碼中找到(在cn.itweknow.springbootmultidatasource.config包下)。spring
主數據源dbone的配置sql
@Configuration
@EnableConfigurationProperties({ DbOneDruidDataSourceProperties.class })
// 指定在哪些包下掃描Mapper
@MapperScan(value = { "cn.itweknow.springbootmultidatasource.dao.mapper.dbone" }, sqlSessionFactoryRef = "dbOneSqlSessionFactory")
@ConditionalOnProperty(name = "dbone.druid.datasource.url", matchIfMissing = false)
public class DbOneDruidDataSourceConfiguration {
/**
* 指定mapper.xml文件的地址
*/
static final String MAPPER_LOCATION = "classpath:sqlmap/dbone/*Mapper.xml";
@Autowired
private DbOneDruidDataSourceProperties dbOneDruidDataSourceProperties;
@Bean(name = "dbOneDruidDataSource", initMethod = "init", destroyMethod = "close")
@ConditionalOnMissingBean(name = "dbOneDruidDataSource")
@Primary
public DruidDataSource dbOneDruidDataSource() throws Exception {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(dbOneDruidDataSourceProperties.getDriverClassName());
dataSource.setUrl(dbOneDruidDataSourceProperties.getUrl());
dataSource.setUsername(dbOneDruidDataSourceProperties.getUsername());
dataSource.setPassword(dbOneDruidDataSourceProperties.getPassword());
return dataSource;
}
@Bean(name = "dbOneTransactionManager")
@ConditionalOnMissingBean(name = "dbOneTransactionManager")
@Primary
public DataSourceTransactionManager dbOneTransactionManager(@Qualifier("dbOneDruidDataSource") DruidDataSource druidDataSource) {
return new DataSourceTransactionManager(druidDataSource);
}
@Bean(name = "dbOneTransactionTemplate")
@ConditionalOnMissingBean(name = "dbOneTransactionTemplate")
@Primary
public TransactionTemplate dbOneTransactionTemplate(@Qualifier("dbOneTransactionManager") PlatformTransactionManager platformTransactionManager) {
return new TransactionTemplate(platformTransactionManager);
}
@Bean(name = "dbOneSqlSessionFactory")
@ConditionalOnMissingBean(name = "dbOneSqlSessionFactory")
@Primary
public SqlSessionFactory dbOneSqlSessionFactory(@Qualifier("dbOneDruidDataSource") DruidDataSource druidDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(druidDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
複製代碼
本例實現的邏輯是從dbtwo中查詢出一條用戶數據,而後根據該用戶的cityId字段去dbone中查詢出對與的城市數據。最後將從兩個庫中查詢出的數據組合起來返回給調用方。具體實現的代碼能夠參考本例源碼,這裏就只粘一下項目的結構,並稍做解釋。數據庫
├── multi-datasource.sql
├── pom.xml
├── README.md
├── springboot-multi-datasource.iml
└── src
└── main
├── java
│ └── cn
│ └── itweknow
│ └── springbootmultidatasource
│ ├── config // 數據源的配置
│ │ ├── DbOneDruidDataSourceConfiguration.java
│ │ ├── DbOneDruidDataSourceProperties.java
│ │ ├── DbTwoDruidDataSourceConfiguration.java
│ │ ├── DbTwoDruidDataSourceProperties.java
│ │ └── DruidDataSourceProperties.java
│ ├── controller // controller
│ │ └── UserController.java
│ ├── dao // 持久層,實體類
│ │ ├── City.java
│ │ ├── example // mybatis example
│ │ │ ├── dbone
│ │ │ │ └── CityExample.java
│ │ │ └── dbtwo
│ │ │ └── UserExample.java
│ │ ├── mapper // mybatis mapper接口
│ │ │ ├── dbone
│ │ │ │ └── CityMapper.java
│ │ │ └── dbtwo
│ │ │ └── UserMapper.java
│ │ └── User.java
│ ├── repository
│ │ ├── CityRepository.java
│ │ └── UserRepository.java
│ ├── service // 業務邏輯
│ │ ├── impl
│ │ │ └── UserServiceImpl.java
│ │ └── UserService.java
│ ├── SpringbootMultiDatasourceApplication.java
│ └── vo
│ └── User.java
└── resources
├── application.properties
└── sqlmap // mapper.xml
├── dbone
│ └── CityMapper.xml
└── dbtwo
└── UserMapper.xml
複製代碼
想要源碼嗎?戳這裏!!!springboot