springboot2.0+mybatis多数据源集成

Posted 无聊的小剑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot2.0+mybatis多数据源集成相关的知识,希望对你有一定的参考价值。

最近在学springboot,把学的记录下来。主要有springboot2.0+mybatis多数据源集成,logback日志集成,springboot单元测试。

一、代码结构如下

二、pom.xml文件如下

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3   <modelVersion>4.0.0</modelVersion>
  4 
  5   <groupId>spring-boot-2</groupId>
  6   <artifactId>spring-boot-2</artifactId>
  7   <version>0.0.1-SNAPSHOT</version>
  8   <packaging>jar</packaging>
  9 
 10   <name>spring-boot-2</name>
 11   <url>http://maven.apache.org</url>
 12 
 13   <properties>
 14     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 15   </properties>
 16 
 17   <dependencies>
 18       <!-- spring boot依赖 -->
 19      <dependency>
 20         <groupId>org.springframework.boot</groupId>
 21         <artifactId>spring-boot-starter-web</artifactId>
 22         <version>2.0.3.RELEASE</version>
 23     </dependency>
 24     
 25     <!-- spring boot测试 -->
 26     <dependency>
 27         <groupId>org.springframework.boot</groupId>
 28         <artifactId>spring-boot-starter-test</artifactId>
 29         <version>2.0.3.RELEASE</version>
 30         <scope>test</scope>
 31     </dependency>
 32     
 33     <!-- spring boot热启动 -->
 34     <dependency>
 35         <groupId>org.springframework.boot</groupId>
 36         <artifactId>spring-boot-devtools</artifactId>
 37         <optional>true</optional>
 38         <version>2.0.3.RELEASE</version>
 39     </dependency>
 40     
 41     <!-- mysql -->
 42     <dependency>
 43         <groupId>mysql</groupId>
 44         <artifactId>mysql-connector-java</artifactId>
 45         <version>5.1.38</version>
 46     </dependency>
 47     
 48     <!-- mybatis -->
 49     <dependency>
 50          <groupId>org.mybatis.spring.boot</groupId>
 51          <artifactId>mybatis-spring-boot-starter</artifactId>
 52          <version>1.3.2</version>
 53     </dependency>
 54     
 55     <!-- alibaba的druid数据库连接池 -->
 56     <dependency>
 57          <groupId>com.alibaba</groupId>
 58          <artifactId>druid-spring-boot-starter</artifactId>
 59          <version>1.1.9</version>
 60     </dependency>
 61   </dependencies>
 62   
 63   <build>
 64     <plugins>
 65         <!-- 规避检查src/main/webapp/WEB-INF下没有web.xml文件 -->
 66         <plugin>
 67             <groupId>org.apache.maven.plugins</groupId>
 68             <artifactId>maven-war-plugin</artifactId>
 69             <version>2.3</version>
 70             <configuration>
 71                 <failOnMissingWebXml>false</failOnMissingWebXml>
 72             </configuration>
 73         </plugin>
 74         <!-- maven热启动 -->
 75         <plugin>
 76             <groupId>org.springframework.boot</groupId>
 77             <artifactId>spring-boot-maven-plugin</artifactId>
 78             <configuration>
 79                 <fork>true</fork>
 80             </configuration>
 81         </plugin>
 82         <!-- 跳过单元测试 -->
 83         <plugin>
 84             <groupId>org.apache.maven.plugins</groupId>
 85             <artifactId>maven-surefire-plugin</artifactId>
 86             <configuration>
 87               <skip>true</skip>
 88             </configuration>
 89         </plugin>
 90         
 91         <!-- 指定jdk版本 -->
 92         <plugin>
 93             <groupId>org.apache.maven.plugins</groupId>
 94             <artifactId>maven-compiler-plugin</artifactId>
 95             <configuration>
 96                 <source>1.8</source>
 97                 <target>1.8</target>
 98             </configuration>
 99         </plugin>
100     </plugins>
101   </build>
102 </project>
View Code

三、编写application.yml文件,springboot支持properties和yml两种格式的配置文件,我使用的是yml文件。使用yml文件需要注意的是只支持空格,不支持tab等,可以下个eclipse的yml插件。

配置文件如下

 1 # 数据源
 2 spring:
 3     datasource:
 4        # master数据源配置
 5        master:
 6            driverClassName: com.mysql.jdbc.Driver
 7            url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
 8            username: root
 9            password: root
10        # cluster数据源配置
11        cluster:
12            driverClassName: com.mysql.jdbc.Driver
13            url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8
14            username: root
15            password: root
16            
View Code

四、编写主从库的配置代码,代码差不多一样,只不过主库配置类的方法上需要加@Primary注解,用来告诉spring默认使用这个配置,主库配置类代码如下

 1 package com.spring.boot.config;
 2 
 3 
 4 import javax.sql.DataSource;
 5 
 6 import org.apache.ibatis.session.SqlSessionFactory;
 7 import org.mybatis.spring.SqlSessionFactoryBean;
 8 import org.mybatis.spring.SqlSessionTemplate;
 9 import org.mybatis.spring.annotation.MapperScan;
10 import org.springframework.beans.factory.annotation.Qualifier;
11 import org.springframework.boot.context.properties.ConfigurationProperties;
12 import org.springframework.boot.jdbc.DataSourceBuilder;
13 import org.springframework.context.annotation.Bean;
14 import org.springframework.context.annotation.Configuration;
15 import org.springframework.context.annotation.Primary;
16 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
17 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
18 
19 /**
20  * mysql从库配置类
21  * @日期: 2018年7月5日 下午10:05:25
22  * @作者: Chendb
23  */
24 @Configuration
25 @MapperScan(basePackages = "com.spring.boot.master.mapper",sqlSessionTemplateRef = "masterSqlSessionTemplate")
26 public class MasterDataSourceConfig {
27 
28     /**
29      * 创建数据源
30      *@return DataSource
31      */
32     @Bean(name = "masterDataSource")
33     @ConfigurationProperties(prefix = "spring.datasource.master")
34     @Primary
35     public DataSource masterDataSource() {
36         return DataSourceBuilder.create().build();
37     }
38     
39     /**
40      * 创建工厂
41      *@param dataSource
42      *@throws Exception
43      *@return SqlSessionFactory
44      */
45     @Bean(name = "masterSqlSessionFactory")
46     @Primary
47     public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
48         SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
49         bean.setDataSource(dataSource);
50         bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
51         return bean.getObject();
52     }
53     
54     /**
55      * 创建事务
56      *@param dataSource
57      *@return DataSourceTransactionManager
58      */
59     @Bean(name = "masterTransactionManager")
60     @Primary
61     public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
62         return new DataSourceTransactionManager(dataSource);
63     }
64     
65     /**
66      * 创建模板
67      *@param sqlSessionFactory  
68      *@return SqlSessionTemplate
69      */
70     @Bean(name = "masterSqlSessionTemplate")
71     @Primary
72     public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
73         return new SqlSessionTemplate(sqlSessionFactory);
74     }
75     
76 }
View Code

从库配置类代码如下

 1 package com.spring.boot.config;
 2 
 3 
 4 import javax.sql.DataSource;
 5 
 6 import org.apache.ibatis.session.SqlSessionFactory;
 7 import org.mybatis.spring.SqlSessionFactoryBean;
 8 import org.mybatis.spring.SqlSessionTemplate;
 9 import org.mybatis.spring.annotation.MapperScan;
10 import org.springframework.beans.factory.annotation.Qualifier;
11 import org.springframework.boot.context.properties.ConfigurationProperties;
12 import org.springframework.boot.jdbc.DataSourceBuilder;
13 import org.springframework.context.annotation.Bean;
14 import org.springframework.context.annotation.Configuration;
15 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
16 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
17 
18 /**
19  * mysql主库配置类
20  * @日期: 2018年7月5日 下午10:05:25
21  * @作者: Chendb
22  */
23 @Configuration
24 @MapperScan(basePackages = "com.spring.boot.mapper.cluster",sqlSessionTemplateRef = "clusterSqlSessionTemplate")
25 public class ClusterDataSourceConfig {
26 
27     /**
28      * 创建数据源
29      *@return DataSource
30      */
31     @Bean(name = "clusterDataSource")
32     @ConfigurationProperties(prefix = "spring.datasource.cluster")
33     public DataSource masterDataSource() {
34         return DataSourceBuilder.create().build();
35     }
36     
37     /**
38      * 创建工厂
39      *@param dataSource
40      *@throws Exception
41      *@return SqlSessionFactory
42      */
43     @Bean(name = "clusterSqlSessionFactory")
44     public SqlSessionFactory masterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource dataSource) throws Exception {
45         SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
46         bean.setDataSource(dataSource);
47         bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/cluster/*.xml"));
48         return bean.getObject();
49     }
50     
51     /**
52      * 创建事务
53      *@param dataSource
54      *@return DataSourceTransactionManager
55      */
56     @Bean(name = "clusterTransactionManager")
57     public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("clusterDataSource") DataSource dataSource) {
58         return new DataSourceTransactionManager(dataSource);
59     }
60     
61     /**
62      * 创建模板
63      *@param sqlSessionFactory  
64      *@return SqlSessionTemplate
65      */
66     @Bean(name = "clusterSqlSessionTemplate")
67     public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("clusterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
68         return new SqlSessionTemplate(sqlSessionFactory);
69     }
70     
71 }
View Code

五、配置mybatis的mapper文件,主库的mapper文件如下

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="com.spring.boot.mapper.cluster.ClusterUserMapper" >
 4     <!-- 结果映射 -->
 5     <resultMap id="BaseMap" type="com.spring.boot.model.UserModel">
 6         <id column="userId" property="userId" jdbcType="INTEGER" />
 7         <result column="userName" property="userName" jdbcType="VARCHAR" />
 8         <result column="password" property="password" jdbcType="VARCHAR" />
 9         <result column="phone" property="phone" jdbcType="VARCHAR" />
10     </resultMap>
11     
12     <!-- 表所有字段 -->
13     <sql id="allColumns">
14         userId, userName, password, phone
15     </sql>
16     
17     <!-- 查询所有数据 -->
18       <select id="getAll" resultMap="BaseMap">
19             SELECT 
20             <include refid="allColumns" />
21             FROM T_USER
22       </select>
23       
24       <!-- 根据主键查询数据 -->
25     <select id="get" resultMap="BaseMap" parameterType="java.util.Map">
26         SELECT
27         <include refid="allColumns" />
28         FROM
29             t_user u
30         WHERE
31             1 = 1 
32         AND userId = #{userId}
33     </select>
34 
35     <!-- 插入数据 -->
36     <insert id="insert" parameterType="java.util.Map">
37         <!--获取最新更新的主键-->
38         <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="userId">
39           SELECT LAST_INSERT_ID() AS userId
40         </selectKey>
41         INSERT INTO T_USER (<include refid="allColumns" />)
42         VALUES (
43             #{userId},
44             #{userName},
45             #{password},
46             #{phone}
47         )
48     </insert>
49     
50      <!-- 修改数据 -->
51     <update id="update" parameterType="java.util.Map">
52         UPDATE T_USER SET
53             userName = #{userName},
54             PASSWORD = #{password},
55             PHONE = #{phone}
56         WHERE userId = #{userId}
57     </update>
58     
59     
60     <!-- 根据主键删除数据 -->
61     <delete id="delete" parameterType="Integer">
62         DELETE FROM T_USER WHERE userId = #{userId}
63     </delete>
64     
65 </mapper>
View Code

从库的mapper文件如下

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="com.spring.boot.mapper.master.MasterUserMapper" >
 4     <!-- 结果映射 -->
 5     <resultMap id="BaseMap" type="com.spring.boot.model.UserModel">
 6         <id column="userId" property="userId" jdbcType="INTEGER" />
 7         <result column="userName" property="userName" jdbcType="VARCHAR" />
 8         <result column="password" property="password" jdbcType="VARCHAR" />
 9         <result column="phone" 

以上是关于springboot2.0+mybatis多数据源集成的主要内容,如果未能解决你的问题,请参考以下文章

Springboot2.0下通过redis实现支持分布式的mybatis二级缓存

SpringBoot2.0 基础案例(10):整合Mybatis框架,集成分页助手插件

SpringBoot2.0之五 优雅整合SpringBoot2.0+MyBatis+druid+PageHelper

学习整合springboot2.0 和 mybatis,实现基本的CRUD

springboot2.0动态多数据源切换

springboot2.0整合mybatis