SpringBoot和Mybatis配置多資料源連接配接多個資料庫
目前業界操作資料庫的架構一般是
Mybatis
,但在很多業務場景下,我們需要在一個工程裡配置多個資料源來實作業務邏輯。在
SpringBoot
中也可以實作多資料源并配合
Mybatis
架構編寫xml檔案來執行SQL。在
SpringBoot
中,配置多資料源的方式十分便捷,
下面開始上代碼:
- 在
檔案中需要添加一些依賴pom.xml
<!-- Spring Boot Mybatis 依賴 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<!-- MySQL 連接配接驅動依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- Druid 資料連接配接池依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
- application.properties 配置兩個資料源配置
# master 資料源配置
master.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
master.datasource.username=root
master.datasource.password=321
master.datasource.driverClassName=com.mysql.jdbc.Driver
# second 資料源配置
second.datasource.url=jdbc:mysql://localhost:3306/springbootdb_second?useUnicode=true&characterEncoding=utf8
second.datasource.username=root
second.datasource.password=321
second.datasource.driverClassName=com.mysql.jdbc.Driver
- 資料源配置
多資料源配置的時候注意,必須要有一個主資料源,即 MasterDataSourceConfig
配置
- @Primary 标志這個 Bean 如果在多個同類 Bean 候選時,該 Bean 優先被考慮。「多資料源配置的時候注意,必須要有一個主資料源,用 @Primary 标志該 Bean
- @MapperScan 掃描 Mapper 接口并容器管理,包路徑精确到 master,為了和下面 cluster 資料源做到精确區分
- @Value 擷取全局配置檔案 application.properties 的 kv 配置,并自動裝配sqlSessionFactoryRef 表示定義了 key ,表示一個唯一 SqlSessionFactory 執行個體
MasterDataSourceConfig
的代碼:
@Configuration
// 掃描 Mapper 接口并容器管理
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
// 精确到 master 目錄,以便跟其他資料源隔離
static final String PACKAGE = "org.spring.springboot.dao.master";
static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";
@Value("${master.datasource.url}")
private String url;
@Value("${master.datasource.username}")
private String user;
@Value("${master.datasource.password}")
private String password;
@Value("${master.datasource.driverClassName}")
private String driverClass;
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "masterTransactionManager")
@Primary
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(masterDataSource());
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(MasterDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
第二個資料源
SecondDataSourceConfig
的配置如下:
@Configuration
// 掃描 Mapper 接口并容器管理
@MapperScan(basePackages = SecondDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {
// 精确到 cluster 目錄,以便跟其他資料源隔離
static final String PACKAGE = "com.springboot.dao.second";
static final String MAPPER_LOCATION = "classpath:mapper/second/*.xml";
@Value("${second.datasource.url}")
private String url;
@Value("${second.datasource.username}")
private String user;
@Value("${second.datasource.password}")
private String password;
@Value("${second.datasource.driverClassName}")
private String driverClass;
@Bean(name = "secondDataSource")
public DataSource clusterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "secondTransactionManager")
public DataSourceTransactionManager clusterTransactionManager() {
return new DataSourceTransactionManager(clusterDataSource());
}
@Bean(name = "secondSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("secondDataSource") DataSource clusterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(clusterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(SecondDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
到此,不同的資料源配置就已經完成,剩下的隻需要将将
Mybatis
的xml檔案和
DAO
層的接口寫好,并在
Service
層注入,直接使用就行。
Service
層的代碼:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private SchoolDao schoolDao;
public UserVo getUser(Long id) {
UserVo userVo = userDao.findById(id);
SchoolVo schoolVo = schoolDao.findByName("清華");
userVo.setSchoolVo(schoolVo);
return userVo;
}
}
Mybatis的xml檔案
UserDao.xml
和
SchoolDao.xml
的内容:
UserDao.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.springboot.dao.master.UserDao">
<resultMap id="BaseResultMap" type="com.springboot.vo.UserVo">
<result column="id" property="id" />
<result column="user_name" property="userName" />
</resultMap>
<sql id="Base_Column_List">
id, user_name
</sql>
<select id="findById" resultMap="BaseResultMap" parameterType="java.lang.Long">
select
<include refid="Base_Column_List" />
from
user
where
id = #{id}
</select>
</mapper>
SchoolDao.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.springboot.dao.second.SchoolDao">
<resultMap id="BaseResultMap" type="com.springboot.vo.SchoolVo">
<result column="id" property="id" />
<result column="school_name" property="schoolName" />
<result column="school_describe" property="schoolDescribe" />
</resultMap>
<sql id="Base_Column_List">
id, school_name, school_describe
</sql>
<select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from
school
where
school_name = #{schoolName}
</select>
</mapper>
TestController
@Controller
@RequestMapping(value = "/api/v1/test")
public class TestController {
@Autowired
private UserService userService;
@RequestMapping(value = "/getUser")
@ResponseBody
public UserVo getUser(@RequestParam(value = "id") Long id) {
return userService.getUser(id);
}
}
建立資料庫和表SQL:
CREATE DATABASE springbootdb;
CREATE DATABASE springbootdb_second;
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 '描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
CREATE TABLE `school` (
`id` bigint(20) NOT NULL,
`school_name` varchar(64) DEFAULT NULL COMMENT '學校名',
`school_describe` varchar(128) DEFAULT NULL COMMENT '學校描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
insert into `springbootdb`.`user` ( `user_name`, `description`) values ( 'shuai', 'so handsome');
insert into `springbootdb_second`.`school` ( `id`, `school_name`, `school_describe`) values ( '1', '清華', '自強不息,厚德載物');
建立好資料後,整個工程的機構如下:
啟動程式,在浏覽器輸入:http://localhost:8080/api/v1/test/getUser?id=1即可傳回結果。
github位址:Spring Boot 教程、技術棧、示例代碼
http://weixin.qq.com/r/fSj44CfE7HqTrWOD931v (二維碼自動識别)