javascript
Spring Boot2 整合 MyBatis 多数据源
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.11.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.gblfy</groupId><artifactId>springboot-mybatis</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-mybatis</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><!--SpringBoot mvc啟動器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--Mysql數(shù)據(jù)庫驅(qū)動--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.28</version><scope>runtime</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><!--lombok 簡化java代碼--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version></dependency><!--druid連接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><!--SpringBoot test 啟動器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><resource><directory>src/main/resources</directory></resource></resources></build></project>首先在 application.properties 中配置數(shù)據(jù)庫基本信息,然后提供兩個(gè) DataSource 即可
spring.datasource.one.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=utf-8 spring.datasource.one.username=root spring.datasource.one.password=root spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.two.url=jdbc:mysql:///test02?useUnicode=true&characterEncoding=utf-8 spring.datasource.two.username=root spring.datasource.two.password=root spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource然后再提供兩個(gè) DataSource,如下:
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;@Configuration public class DataSourceConfig {@Bean@ConfigurationProperties(prefix = "spring.datasource.one")DataSource dsOne() {return DruidDataSourceBuilder.create().build();}@Bean@ConfigurationProperties(prefix = "spring.datasource.two")DataSource dsTwo() {return DruidDataSourceBuilder.create().build();} }MyBatis 配置
要提供兩個(gè) Bean,因此這里兩個(gè)數(shù)據(jù)源我將在兩個(gè)類中分開來配置,首先來看第一個(gè)數(shù)據(jù)源的配置:
創(chuàng)建 MyBatisConfigOne 類,首先指明該類是一個(gè)配置類,配置類中要掃描的包是 org.javaboy.mybatis.mapper1 ,即該包下的 Mapper 接口將操作 dsOne 中的數(shù)據(jù),對應(yīng)的 SqlSessionFactory 和 SqlSessionTemplate 分別是 sqlSessionFactory1 和 sqlSessionTemplate1,在 MyBatisConfigOne 內(nèi)部,分別提供 SqlSessionFactory 和 SqlSessionTemplate 即可, SqlSessionFactory 根據(jù) dsOne 創(chuàng)建,然后再根據(jù)創(chuàng)建好的SqlSessionFactory 創(chuàng)建一個(gè) SqlSessionTemplate。
這里配置完成后,依據(jù)這個(gè)配置,再來配置第二個(gè)數(shù)據(jù)源即可:
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.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import javax.annotation.Resource; import javax.sql.DataSource;@Configuration @MapperScan(basePackages = "com.gblfy.springboot.mybatis.mapper2",sqlSessionFactoryRef = "sqlSessionFactory2",sqlSessionTemplateRef = "sqlSessionTemplate2") public class MyBatisConfigTwo {@Resource(name = "dsTwo")DataSource dsTwo;@BeanSqlSessionFactory sqlSessionFactory2() {SqlSessionFactory sessionFactory = null;try {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dsTwo);sessionFactory = bean.getObject();} catch (Exception e) {e.printStackTrace();}return sessionFactory;}@BeanSqlSessionTemplate sqlSessionTemplate2() {return new SqlSessionTemplate(sqlSessionFactory2());} }好了,這樣 MyBatis 多數(shù)據(jù)源基本上就配置好了,接下來只需要在 org.javaboy.mybatis.mapper1 和 org.javaboy.mybatis.mapper2 包中提供不同的 Mapper,Service 中注入不同的 Mapper 就可以操作不同的數(shù)據(jù)源。
com.gblfy.springboot.mybatis.mapper1中的 mapper:
對應(yīng)的 XML 文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.gblfy.springboot.mybatis.mapper1.UserMapperOne"><select id="getAllUser" resultType="com.gblfy.springboot.mybatis.entity.User">select * from user;</select> </mapper>com.gblfy.springboot.mybatis.mapper2中的 mapper:
import com.gblfy.springboot.mybatis.entity.User;import java.util.List;public interface UserMapper {List<User> getAllUser(); }對應(yīng)的 XML 文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.gblfy.springboot.mybatis.mapper2.UserMapper"><select id="getAllUser" resultType="com.gblfy.springboot.mybatis.entity.User">select * from user;</select> </mapper>實(shí)體類:
import lombok.Data;import java.io.Serializable; import java.time.LocalDateTime;@Data public class User implements Serializable {//主鍵private Long id;//姓名private String name;//年齡private Integer age;//郵箱private String email;//創(chuàng)建時(shí)間private LocalDateTime createTime; }數(shù)據(jù)庫腳本;
one
two
DROP TABLE IF EXISTS user;CREATE TABLE user (id BIGINT(20) NOT NULL COMMENT '主鍵ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年齡',email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',create_time DATETIME DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',PRIMARY KEY (id) );DELETE FROM user;INSERT INTO user (id, name, age, email, create_time) VALUES (1, 'Jone2', 18, 'test1@gblfy.com','2019-01-11 14:20:20'), (2, 'Jack2', 20, 'test2@gblfy.com','2019-02-05 11:12:22'), (3, 'Tom2', 28, 'test3@gblfy.com','2019-02-14 08:31:16'), (4, 'Sandy2', 21, 'test4@gblfy.com','2019-01-14 09:15:15'), (5, 'Billie2', 24, 'test5@gblfy.com','2019-01-14 09:48:16');寫一個(gè)測試controller
import com.gblfy.springboot.mybatis.entity.User; import com.gblfy.springboot.mybatis.mapper1.UserMapperOne; import com.gblfy.springboot.mybatis.mapper2.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController public class PageController {@Autowiredprivate UserMapperOne userMapperOne;@Autowiredprivate UserMapper userMapper;@GetMapping("/one")public List<User> getOneList() {return userMapperOne.getAllUser();}@GetMapping("/two")public List<User> getTwoList() {return userMapper.getAllUser();} }啟動項(xiàng)目:
依次訪問
http://localhost:8080/one
http://localhost:8080/two
總結(jié)
以上是生活随笔為你收集整理的Spring Boot2 整合 MyBatis 多数据源的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux Shell脚本专栏_批量主机
- 下一篇: 快速开发工作流_03_集成在线流程设计器