1.項目代碼結構:
2,導入基本依賴:記得需要導入mysql驅動mysql-connector-java
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency> <!-- MySql驅動 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--druid 依賴-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
3.配置多數據源
注意:Spring Boot 2.X 版本不再支持配置繼承,多數據源的話每個數據源的所有配置都需要單獨配置,否則配置不會生效。
spring:
datasource:
db1:
url: jdbc:mysql://127.0.0.1:3306/db01?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
username: root
password:
driver-class-name: com.mysql.cj.jdbc.Driver
# 初始化時建立物理連接的個數。初始化發生在顯示調用 init 方法,或者第一次 getConnection 時
initialSize: 5
# 最小連接池數量
minIdle: 5
# 最大連接池數量
maxActive: 10
# 獲取連接時最大等待時間,單位毫秒。配置了 maxWait 之後,缺省啓用公平鎖,併發效率會有所下降,如果需要可以通過配置 useUnfairLock 屬性爲 true 使用非公平鎖。
maxWait: 60000
# Destroy 線程會檢測連接的間隔時間,如果連接空閒時間大於等於 minEvictableIdleTimeMillis 則關閉物理連接。
timeBetweenEvictionRunsMillis: 60000
# 連接保持空閒而不被驅逐的最小時間
minEvictableIdleTimeMillis: 300000
# 用來檢測連接是否有效的 sql 因數據庫方言而異, 例如 oracle 應該寫成 SELECT 1 FROM DUAL
validationQuery: SELECT 1
# 建議配置爲 true,不影響性能,並且保證安全性。申請連接的時候檢測,如果空閒時間大於 timeBetweenEvictionRunsMillis,執行 validationQuery 檢測連接是否有效。
testWhileIdle: true
# 申請連接時執行 validationQuery 檢測連接是否有效,做了這個配置會降低性能。
testOnBorrow: false
# 歸還連接時執行 validationQuery 檢測連接是否有效,做了這個配置會降低性能。
testOnReturn: false
# 是否自動回收超時連接
removeAbandoned: true
# 超時時間 (以秒數爲單位)
remove-abandoned-timeout: 1800
db2:
url: jdbc:mysql://127.0.0.1:3306/db02?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
username: root
password:
driver-class-name: com.mysql.cj.jdbc.Driver
# 初始化時建立物理連接的個數。初始化發生在顯示調用 init 方法,或者第一次 getConnection 時
initialSize: 6
# 最小連接池數量
minIdle: 6
# 最大連接池數量
maxActive: 10
# 獲取連接時最大等待時間,單位毫秒。配置了 maxWait 之後,缺省啓用公平鎖,併發效率會有所下降,如果需要可以通過配置 useUnfairLock 屬性爲 true 使用非公平鎖。
maxWait: 60000
# Destroy 線程會檢測連接的間隔時間,如果連接空閒時間大於等於 minEvictableIdleTimeMillis 則關閉物理連接。
timeBetweenEvictionRunsMillis: 60000
# 連接保持空閒而不被驅逐的最小時間
minEvictableIdleTimeMillis: 300000
# 用來檢測連接是否有效的 sql 因數據庫方言而異, 例如 oracle 應該寫成 SELECT 1 FROM DUAL
validationQuery: SELECT 1
# 建議配置爲 true,不影響性能,並且保證安全性。申請連接的時候檢測,如果空閒時間大於 timeBetweenEvictionRunsMillis,執行 validationQuery 檢測連接是否有效。
testWhileIdle: true
# 申請連接時執行 validationQuery 檢測連接是否有效,做了這個配置會降低性能。
testOnBorrow: false
# 歸還連接時執行 validationQuery 檢測連接是否有效,做了這個配置會降低性能。
testOnReturn: false
# 是否自動回收超時連接
removeAbandoned: true
# 超時時間 (以秒數爲單位)
remove-abandoned-timeout: 1800
# WebStatFilter 用於採集 web-jdbc 關聯監控的數據。
web-stat-filter:
# 是否開啓 WebStatFilter 默認是 true
enabled: true
# 需要攔截的 url
url-pattern: /*
# 排除靜態資源的請求
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
# Druid 內置提供了一個 StatViewServlet 用於展示 Druid 的統計信息。
stat-view-servlet:
#是否啓用 StatViewServlet 默認值 true
enabled: true
# 需要攔截的 url
url-pattern: /druid/*
# 允許清空統計數據
reset-enable: true
login-username: druid
login-password: druid
4.配置類
主數據源配置類:
package com.study.multisource.config;
import com.alibaba.druid.pool.DruidDataSource;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;
/**
* @author liuhui
* @date 2020/5/14 16:56
*/
@Configuration
@MapperScan(basePackages = "com.study.multisource.mybatis.oneDao",sqlSessionFactoryRef = "oneSqlSessionFactory")
public class DataSourceConfig1 {
// 將這個對象放入Spring容器中
@Bean(name = "oneDataSource")
// 表示這個數據源是默認數據源
@Primary
// 讀取application.properties中的配置參數映射成爲一個對象
// prefix表示參數的前綴
@ConfigurationProperties(prefix = "spring.datasource.db1")
public DataSource getDateSource1()
{
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "oneSqlSessionFactory")
// 表示這個數據源是默認數據源
@Primary
// @Qualifier表示查找Spring容器中名字爲oneDataSource的對象
public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource datasource)
throws Exception
{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 設置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/one/*.xml"));
return bean.getObject();
}
@Bean("oneSqlSessionTemplate")
// 表示這個數據源是默認數據源
@Primary
public SqlSessionTemplate oneSqlSessionTemplate(
@Qualifier("oneSqlSessionFactory") SqlSessionFactory sessionFactory)
{
return new SqlSessionTemplate(sessionFactory);
}
}
次數據源配置類:
package com.study.multisource.config;
import com.alibaba.druid.pool.DruidDataSource;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;
/**
* @author liuhui
* @date 2020/5/14 17:07
*/
@Configuration
@MapperScan(basePackages = "com.study.multisource.mybatis.twoDao",sqlSessionFactoryRef = "twoSqlSessionFactory")
public class DataSourceConfig2 {
// 將這個對象放入Spring容器中
@Bean(name = "twoDataSource")
// 讀取application.properties中的配置參數映射成爲一個對象
// prefix表示參數的前綴
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSource getDateSource1()
{
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "twoSqlSessionFactory")
// 表示這個數據源是默認數據源
@Primary
// @Qualifier表示查找Spring容器中名字爲oneDataSource的對象
public SqlSessionFactory oneSqlSessionFactory(@Qualifier("twoDataSource") DataSource datasource)
throws Exception
{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 設置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/two/*.xml"));
return bean.getObject();
}
@Bean("twoSqlSessionTemplate")
// 表示這個數據源是默認數據源
@Primary
public SqlSessionTemplate oneSqlSessionTemplate(
@Qualifier("twoSqlSessionFactory") SqlSessionFactory sessionFactory)
{
return new SqlSessionTemplate(sessionFactory);
}
}
5.啓動類:
注意:不需要使用自動配置,那麼需要取消加載對應的自動配置類。
在啓動類關閉 Spring Boot 對數據源的自動化配置,由我們手動進行多數據源的配置:
package com.study.multisource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MultisourceApplication {
public static void main(String[] args) {
SpringApplication.run(MultisourceApplication.class, args);
}
}
6.測試使用的表:
#建在db01庫下
CREATE TABLE `user` (
`id` bigint(20) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#建在db02庫下
CREATE TABLE `t_item_order` (
`id` int(9) NOT NULL AUTO_INCREMENT COMMENT '自增id',
`item_id` int(4) NOT NULL COMMENT '商品id',
`item_name` varchar(50) NOT NULL DEFAULT '' COMMENT '商品名稱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='商品表';
7.測試表對應的實體類:
package com.study.multisource.entity;
import lombok.Data;
import lombok.ToString;
/**
* @author liuhui
* @date 2020/5/14 17:32
*/
@Data
@ToString
public class ItemOrder {
private Integer id;
private Integer itemId;
private String itemName;
}
package com.study.multisource.entity;
import lombok.Data;
import lombok.ToString;
/**
* @author liuhui
* @date 2020/5/14 17:29
*/
@Data
@ToString
public class User {
private Long id;
private String name;
}
8.持久層:dao層接口(注意:我將其放在不同目錄下方便區分管理):
package com.study.multisource.mybatis.oneDao;
import com.study.multisource.entity.User;
import java.util.List;
public interface UserMapper {
List<User> getAllUser();
}
package com.study.multisource.mybatis.twoDao;
import com.study.multisource.entity.ItemOrder;
import java.util.List;
public interface ItemOrderMapper {
List<ItemOrder> getAllItemOrder();
}
dao層對應的xml配置文件:
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.study.multisource.mybatis.oneDao.UserMapper">
<select id="getAllUser" resultType="com.study.multisource.entity.User">
select *
from `user`
</select>
</mapper>
ItemOrderMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.study.multisource.mybatis.twoDao.ItemOrderMapper">
<resultMap id="BaseResultMap" type="com.study.multisource.entity.ItemOrder">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="item_id" jdbcType="INTEGER" property="itemId" />
<result column="item_name" jdbcType="VARCHAR" property="itemName" />
</resultMap>
<select id="getAllItemOrder" resultMap="BaseResultMap">
select *
from t_item_order
</select>
</mapper>
service層:
接口:
package com.study.multisource.service;
import com.study.multisource.entity.ItemOrder;
import com.study.multisource.entity.User;
import java.util.List;
/**
* @author liuhui
* @date 2020/5/14 17:24
*/
public interface TestService {
public List<User> getAllUser();
public List<ItemOrder> getAllItemOrder();
}
實現類:
package com.study.multisource.service.impl;
import com.study.multisource.entity.ItemOrder;
import com.study.multisource.entity.User;
import com.study.multisource.mybatis.oneDao.UserMapper;
import com.study.multisource.mybatis.twoDao.ItemOrderMapper;
import com.study.multisource.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author liuhui
* @date 2020/5/14 17:25
*/
@Service
public class TestServiceImpl implements TestService {
@Autowired
UserMapper userMapper;
@Autowired
ItemOrderMapper itemOrderMapper;
@Override
public List<User> getAllUser() {
return userMapper.getAllUser();
}
@Override
public List<ItemOrder> getAllItemOrder() {
return itemOrderMapper.getAllItemOrder();
}
}
下面進行測試:
package com.study.multisource.multisource;
import com.study.multisource.service.TestService;
import lombok.ToString;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MultisourceApplicationTests {
@Autowired
TestService testService;
@Test
void contextLoads() {
}
@Test
void testS(){
System.out.println(testService.getAllItemOrder());
System.out.println(testService.getAllUser());
}
}
結果:
2020-05-16 08:54:17.566 INFO 12556 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
[ItemOrder(id=1, itemId=101, itemName=泡泡糖)]
--------------------------
2020-05-16 08:54:17.752 INFO 12556 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-2} inited
[User(id=2, name=Lucy), User(id=4, name=Lina)]
當然也可以不用向上面分的那麼細,也可以把多個數據源下面的XxxMapper.xml放在同一個目錄下,同時就可以把多個數據源的配置類解析的xml路徑寫成同一個了
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));