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>

三、编写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            

四、编写主从库的配置代码,代码差不多一样,只不过主库配置类的方法上需要加@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 }

从库配置类代码如下

 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 }

五、配置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>

从库的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" 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" useGeneratedKeys="true" keyProperty="userId" keyColumn="userId">
37         INSERT INTO T_USER (userName,password,phone)
38         VALUES (
39             #{userName},
40             #{password},
41             #{phone}
42         )
43     </insert>
44
45      <!-- 修改数据 -->
46     <update id="update" parameterType="java.util.Map">
47         UPDATE T_USER SET
48             userName = #{userName},
49             PASSWORD = #{password},
50             PHONE = #{phone}
51         WHERE userId = #{userId}
52     </update>
53
54
55     <!-- 根据主键删除数据 -->
56     <delete id="delete" parameterType="Integer">
57         DELETE FROM T_USER WHERE userId = #{userId}
58     </delete>
59
60 </mapper>

六、编写mybatis的dao层,这里不需要编写具体的dao层实现,只写接口类,只要保证mapper配置文件的命名空间和接口类的全限定名一致并且接口方法名和mapper文件的sql标识符对应即可

主库的接口类如下

 1 package com.spring.boot.mapper.master;
 2
 3 import java.util.List;
 4
 5 import com.spring.boot.model.UserModel;
 6
 7 public interface MasterUserMapper {
 8
 9     /**
10      * 获取全部用户数据
11      *@return List<UserModel> 用户列表
12      */
13     List<UserModel> getAll();
14
15     /**
16      * 获取用户数据
17      *@param userId 用户id
18      *@return UserModel 用户数据
19      */
20     UserModel get(Integer userId);
21
22     /**
23      * 保存用户
24      *@param userModel 用户数据
25      *@return Integer 是否成功,1成功,0失败
26      */
27     Integer insert(UserModel userModel);
28
29     /**
30      * 更新用户
31      *@param userModel 用户数据
32      *@return Integer 是否成功,1成功,0失败
33      */
34     Integer update(UserModel userModel);
35
36     /**
37      * 删除用户
38      *@param userId 用户id
39      *@return Integer 是否成功,1成功,0失败
40      */
41     Integer delete(Integer userId);
42 }

从库的接口类如下

 1 package com.spring.boot.mapper.cluster;
 2
 3 import java.util.List;
 4
 5 import com.spring.boot.model.UserModel;
 6
 7 public interface ClusterUserMapper {
 8     /**
 9      * 获取全部用户数据
10      *@return List<UserModel> 用户列表
11      */
12     List<UserModel> getAll();
13
14     /**
15      * 获取用户数据
16      *@param userId 用户id
17      *@return UserModel 用户数据
18      */
19     UserModel get(Integer userId);
20
21     /**
22      * 保存用户
23      *@param userModel 用户数据
24      *@return Integer 是否成功,1成功,0失败
25      */
26     Integer insert(UserModel userModel);
27
28     /**
29      * 更新用户
30      *@param userModel 用户数据
31      *@return Integer 是否成功,1成功,0失败
32      */
33     Integer update(UserModel userModel);
34
35     /**
36      * 删除用户
37      *@param userId 用户id
38      *@return Integer 是否成功,1成功,0失败
39      */
40     Integer delete(Integer userId);
41 }

七、springboot启动类

 1 package com.spring.boot;
 2
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6
 7 /**
 8  * springboot启动类
 9  * @日期: 2018年7月5日 下午10:03:36
10  * @作者: Chendb
11  */
12 @SpringBootApplication
13 @MapperScan("com.spring.boot.mapper")
14 public class Application {
15
16     public static void main(String[] args) {
17         SpringApplication.run(Application.class, args);
18     }
19
20 }

八、实体类和数据库表

 1 package com.spring.boot.model;
 2
 3 import java.io.Serializable;
 4
 5 public class UserModel implements Serializable{
 6     /**
 7      *
 8      */
 9     private static final long serialVersionUID = 1L;
10
11     /**
12      * 用户id
13      */
14     private Integer userId;
15
16     /**
17      * 用户名称
18      */
19     private String userName;
20
21     /**
22      * 用户密码
23      */
24     private String password;
25
26     /**
27      * 电话
28      */
29     private String phone;
30
31     /**
32      * 获取用户id
33      *@return Integer 用户id
34      */
35     public Integer getUserId() {
36         return userId;
37     }
38
39     /**
40      * 设置用户id
41      *@param userId 用户id
42      *@return void
43      */
44     public void setUserId(Integer userId) {
45         this.userId = userId;
46     }
47
48     /**
49      * 获取用户名称
50      *@return String 用户名称
51      */
52     public String getUserName() {
53         return userName;
54     }
55
56     /**
57      * 设置用户名称
58      *@param userName 用户名称
59      *@return void
60      */
61     public void setUserName(String userName) {
62         this.userName = userName;
63     }
64
65     /**
66      * 获取用户密码
67      *@return String 用户密码
68      */
69     public String getPassword() {
70         return password;
71     }
72
73     /**
74      * 设置用户密码
75      *@param password 用户密码
76      *@return void
77      */
78     public void setPassword(String password) {
79         this.password = password;
80     }
81
82     /**
83      * 获取电话
84      *@return String 电话
85      */
86     public String getPhone() {
87         return phone;
88     }
89
90     /**
91      * 设置电话
92      *@param phone 电话
93      *@return void
94      */
95     public void setPhone(String phone) {
96         this.phone = phone;
97     }
98 }

 1 /*
 2 Navicat MySQL Data Transfer
 3
 4 Source Server         : local
 5 Source Server Version : 50713
 6 Source Host           : localhost:3306
 7 Source Database       : test2
 8
 9 Target Server Type    : MYSQL
10 Target Server Version : 50713
11 File Encoding         : 65001
12
13 Date: 2018-07-06 23:14:03
14 */
15
16 SET FOREIGN_KEY_CHECKS=0;
17
18 -- ----------------------------
19 -- Table structure for t_user
20 -- ----------------------------
21 DROP TABLE IF EXISTS `t_user`;
22 CREATE TABLE `t_user` (
23   `userId` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘用户id‘,
24   `userName` varchar(255) NOT NULL COMMENT ‘用户名称‘,
25   `password` varchar(255) NOT NULL COMMENT ‘用户密码‘,
26   `phone` varchar(255) NOT NULL COMMENT ‘电话‘,
27   PRIMARY KEY (`userId`)
28 ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

九、控制层以及单元测试类

 1 package com.spring.boot.controller;
 2
 3 import java.util.List;
 4
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8
 9 import com.spring.boot.mapper.cluster.ClusterUserMapper;
10 import com.spring.boot.mapper.master.MasterUserMapper;
11 import com.spring.boot.model.UserModel;
12
13 /**
14  * 用户控制层
15  * @日期: 2018年7月5日 下午11:18:04
16  * @作者: Chendb
17  */
18 @RestController
19 public class UserController {
20
21     @Autowired
22     private MasterUserMapper masterUserMapper;
23
24     @Autowired
25     private ClusterUserMapper clusterUserMapper;
26
27     /************************主库控制层接口-start******************************/
28     @RequestMapping("user/getAllMaster")
29     public List<UserModel> getAllMaster() {
30         return masterUserMapper.getAll();
31     }
32
33     @RequestMapping("user/getMaster")
34     public UserModel getUserMaster(Integer userId) {
35         return masterUserMapper.get(userId);
36     }
37
38     @RequestMapping("user/insertMaster")
39     public Integer insertMaster(UserModel userModel) {
40         masterUserMapper.insert(userModel);
41         // 必须使用对象获取id,否则无法获取到主键,而是获取到0(插入失败)或者1(插入成功)
42         return userModel.getUserId();
43     }
44
45     @RequestMapping("user/updateMaster")
46     public Integer updateMaster(UserModel userModel) {
47         return masterUserMapper.update(userModel);
48     }
49
50     @RequestMapping("user/deleteMaster")
51     public Integer deleteMaster(Integer userId) {
52         return masterUserMapper.delete(userId);
53     }
54     /************************主库控制层接口-end******************************/
55
56     /************************从库控制层接口-start******************************/
57     @RequestMapping("user/getAllCluster")
58     public List<UserModel> getAllCluster() {
59         return clusterUserMapper.getAll();
60     }
61
62     @RequestMapping("user/getCluster")
63     public UserModel getUserCluster(Integer userId) {
64         return clusterUserMapper.get(userId);
65     }
66
67     @RequestMapping("user/insertCluster")
68     public Integer insertCluster(UserModel userModel) {
69         clusterUserMapper.insert(userModel);
70         // 必须使用对象获取id,否则无法获取到主键,而是获取到0(插入失败)或者1(插入成功)
71         return userModel.getUserId();
72     }
73
74     @RequestMapping("user/updateCluster")
75     public Integer updateCluster(UserModel userModel) {
76         return clusterUserMapper.update(userModel);
77     }
78
79     @RequestMapping("user/deleteCluster")
80     public Integer deleteCluster(Integer userId) {
81         return clusterUserMapper.delete(userId);
82     }
83     /************************从库控制层接口-end******************************/
84 }

  1 package com.spring.boot;
  2
  3 import org.junit.Before;
  4 import org.junit.Test;
  5 import org.junit.runner.RunWith;
  6 import org.springframework.beans.factory.annotation.Autowired;
  7 import org.springframework.boot.test.context.SpringBootTest;
  8 import org.springframework.http.MediaType;
  9 import org.springframework.test.context.junit4.SpringRunner;
 10 import org.springframework.test.web.servlet.MockMvc;
 11 import org.springframework.test.web.servlet.ResultActions;
 12 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
 13 import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
 14 import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
 15 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
 16 import org.springframework.web.context.WebApplicationContext;
 17
 18 @RunWith(SpringRunner.class)
 19 @SpringBootTest
 20 public class UserControllerTest {
 21
 22     @Autowired
 23     private WebApplicationContext context;
 24
 25     private MockMvc mvc;
 26
 27     @Before
 28     public void setUp() throws Exception {
 29         this.mvc = MockMvcBuilders.webAppContextSetup(context).build();
 30     }
 31
 32     /************************主库控制层接口测试-start******************************/
 33     @Test
 34     public void testInsertMaster() throws Exception {
 35         ResultActions action = mvc.perform(MockMvcRequestBuilders
 36                 .post("/user/insertMaster")
 37                 .param("userName", "testName")
 38                 .param("password", "password")
 39                 .param("phone", "13578236975")
 40                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
 41                 .accept(MediaType.APPLICATION_JSON))
 42                 .andExpect(MockMvcResultMatchers.status().isOk())
 43                 .andDo(MockMvcResultHandlers.print());
 44         String userId = action.andReturn().getResponse().getContentAsString();
 45
 46         System.out.println("userId:" + userId);
 47     }
 48
 49     @Test
 50     public void testGetAllMaster() throws Exception {
 51
 52         // 先保存,确保有数据
 53         mvc.perform(MockMvcRequestBuilders
 54                 .post("/user/insertMaster")
 55                 .param("userName", "testName")
 56                 .param("password", "password")
 57                 .param("phone", "13578236975")
 58                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
 59                 .accept(MediaType.APPLICATION_JSON))
 60                 .andExpect(MockMvcResultMatchers.status().isOk())
 61                 .andDo(MockMvcResultHandlers.print());
 62
 63         mvc.perform(MockMvcRequestBuilders
 64                 .get("/user/getAllMaster")
 65                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
 66                 .accept(MediaType.APPLICATION_JSON))
 67                 .andExpect(MockMvcResultMatchers.status().isOk())
 68                 .andDo(MockMvcResultHandlers.print());
 69     }
 70
 71     @Test
 72     public void testGetMaster() throws Exception {
 73         // 先保存,确保有数据
 74         ResultActions action = mvc.perform(MockMvcRequestBuilders
 75                 .post("/user/insertMaster")
 76                 .param("userName", "testName1")
 77                 .param("password", "password1")
 78                 .param("phone", "13578236975")
 79                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
 80                 .accept(MediaType.APPLICATION_JSON))
 81                 .andExpect(MockMvcResultMatchers.status().isOk())
 82                 .andDo(MockMvcResultHandlers.print());
 83
 84         String userId = action.andReturn().getResponse().getContentAsString();
 85         System.out.println("userId:" + userId);
 86
 87         mvc.perform(MockMvcRequestBuilders
 88                 .get("/user/getMaster")
 89                 .param("userId", userId)
 90                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
 91                 .accept(MediaType.APPLICATION_JSON))
 92                 .andExpect(MockMvcResultMatchers.status().isOk())
 93                 .andDo(MockMvcResultHandlers.print());
 94     }
 95
 96     @Test
 97     public void testUpdateMaster() throws Exception {
 98         // 先保存,确保有数据
 99         ResultActions action = mvc.perform(MockMvcRequestBuilders
100                 .post("/user/insertMaster")
101                 .param("userName", "testName1")
102                 .param("password", "password1")
103                 .param("phone", "13578236975")
104                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
105                 .accept(MediaType.APPLICATION_JSON))
106                 .andExpect(MockMvcResultMatchers.status().isOk())
107                 .andDo(MockMvcResultHandlers.print());
108
109         String userId = action.andReturn().getResponse().getContentAsString();
110         System.out.println("userId:" + userId);
111
112         mvc.perform(MockMvcRequestBuilders
113                 .post("/user/updateMaster")
114                 .param("userName", "修改")
115                 .param("password", "password")
116                 .param("phone", "13578236975")
117                 .param("userId", userId)
118                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
119                 .accept(MediaType.APPLICATION_JSON))
120                 .andExpect(MockMvcResultMatchers.status().isOk())
121                 .andDo(MockMvcResultHandlers.print());
122     }
123
124     @Test
125     public void testDeleteMaster() throws Exception {
126
127         // 先保存,确保有数据
128         ResultActions action = mvc.perform(MockMvcRequestBuilders
129                 .post("/user/insertMaster")
130                 .param("userName", "testName1")
131                 .param("password", "password1")
132                 .param("phone", "13578236975")
133                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
134                 .accept(MediaType.APPLICATION_JSON))
135                 .andExpect(MockMvcResultMatchers.status().isOk())
136                 .andDo(MockMvcResultHandlers.print());
137
138         String userId = action.andReturn().getResponse().getContentAsString();
139         System.out.println("userId:" + userId);
140
141         mvc.perform(MockMvcRequestBuilders
142                 .delete("/user/deleteMaster")
143                 .param("userId", userId)
144                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
145                 .accept(MediaType.APPLICATION_JSON))
146                 .andExpect(MockMvcResultMatchers.status().isOk())
147                 .andDo(MockMvcResultHandlers.print());
148     }
149     /************************主库控制层接口测试-end******************************/
150
151     /************************从库控制层接口测试-start******************************/
152
153     @Test
154     public void testInsertCluster() throws Exception {
155         mvc.perform(MockMvcRequestBuilders
156                 .post("/user/insertCluster")
157                 .param("userName", "testName")
158                 .param("password", "password")
159                 .param("phone", "13578236975")
160                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
161                 .accept(MediaType.APPLICATION_JSON))
162                 .andExpect(MockMvcResultMatchers.status().isOk())
163                 .andDo(MockMvcResultHandlers.print());
164     }
165
166     @Test
167     public void testGetAllCluster() throws Exception {
168         // 先保存,确保有数据
169         ResultActions action = mvc.perform(MockMvcRequestBuilders
170                 .post("/user/insertCluster")
171                 .param("userName", "testName1")
172                 .param("password", "password1")
173                 .param("phone", "13578236975")
174                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
175                 .accept(MediaType.APPLICATION_JSON))
176                 .andExpect(MockMvcResultMatchers.status().isOk())
177                 .andDo(MockMvcResultHandlers.print());
178
179         String userId = action.andReturn().getResponse().getContentAsString();
180         System.out.println("userId:" + userId);
181
182         mvc.perform(MockMvcRequestBuilders
183                 .get("/user/getAllCluster")
184                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
185                 .accept(MediaType.APPLICATION_JSON))
186                 .andExpect(MockMvcResultMatchers.status().isOk())
187                 .andDo(MockMvcResultHandlers.print());
188     }
189
190     @Test
191     public void testGetCluster() throws Exception {
192         // 先保存,确保有数据
193         ResultActions action = mvc.perform(MockMvcRequestBuilders
194                 .post("/user/insertCluster")
195                 .param("userName", "testName1")
196                 .param("password", "password1")
197                 .param("phone", "13578236975")
198                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
199                 .accept(MediaType.APPLICATION_JSON))
200                 .andExpect(MockMvcResultMatchers.status().isOk())
201                 .andDo(MockMvcResultHandlers.print());
202
203         String userId = action.andReturn().getResponse().getContentAsString();
204         System.out.println("userId:" + userId);
205
206         mvc.perform(MockMvcRequestBuilders
207                 .get("/user/getCluster")
208                 .param("userId", userId)
209                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
210                 .accept(MediaType.APPLICATION_JSON))
211                 .andExpect(MockMvcResultMatchers.status().isOk())
212                 .andDo(MockMvcResultHandlers.print());
213     }
214
215     @Test
216     public void testUpdateCluster() throws Exception {
217         // 先保存,确保有数据
218         ResultActions action = mvc.perform(MockMvcRequestBuilders
219                 .post("/user/insertCluster")
220                 .param("userName", "testName1")
221                 .param("password", "password1")
222                 .param("phone", "13578236975")
223                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
224                 .accept(MediaType.APPLICATION_JSON))
225                 .andExpect(MockMvcResultMatchers.status().isOk())
226                 .andDo(MockMvcResultHandlers.print());
227
228         String userId = action.andReturn().getResponse().getContentAsString();
229         System.out.println("userId:" + userId);
230
231         mvc.perform(MockMvcRequestBuilders
232                 .post("/user/updateCluster")
233                 .param("userName", "testName修改")
234                 .param("password", "password")
235                 .param("phone", "13578236975")
236                 .param("userId", userId)
237                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
238                 .accept(MediaType.APPLICATION_JSON))
239                 .andExpect(MockMvcResultMatchers.status().isOk())
240                 .andDo(MockMvcResultHandlers.print());
241     }
242
243     @Test
244     public void testDeleteCluster() throws Exception {
245
246         // 先保存,确保有数据
247         ResultActions action = mvc.perform(MockMvcRequestBuilders
248                 .post("/user/insertCluster")
249                 .param("userName", "testName1")
250                 .param("password", "password1")
251                 .param("phone", "13578236975")
252                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
253                 .accept(MediaType.APPLICATION_JSON))
254                 .andExpect(MockMvcResultMatchers.status().isOk())
255                 .andDo(MockMvcResultHandlers.print());
256
257         String userId = action.andReturn().getResponse().getContentAsString();
258         System.out.println("userId:" + userId);
259
260         mvc.perform(MockMvcRequestBuilders
261                 .delete("/user/deleteCluster")
262                 .param("userId", userId)
263                 .content(MediaType.APPLICATION_JSON_UTF8_VALUE)
264                 .accept(MediaType.APPLICATION_JSON))
265                 .andExpect(MockMvcResultMatchers.status().isOk())
266                 .andDo(MockMvcResultHandlers.print());
267     }
268     /************************从库控制层接口测试-end******************************/
269 }

十、springboot已经包含了logback的相关jar包,只要在类路径下有名为“logback-spring”的xml文件即可进行日志打印,具体配置如下

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <configuration scan="true" scanPeriod="10 seconds">
 3     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
 4         <encoder>
 5             <!-- do not add line number output , it will slow down the execution speed -->
 6             <pattern>%d{HH:mm:ss.SSS} [%thread] %level %logger{36} - %msg%n</pattern>
 7         </encoder>
 8     </appender>
 9     <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
10         <!-- 按天来回滚,如果需要按小时来回滚,则设置为{yyyy-MM-dd_HH} -->
11         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
12             <!--文件路径和文件名称-->
13             <fileNamePattern>${catalina.base}/logs/test.%d{yyyy-MM-dd}.log</fileNamePattern>
14             <!-- 如果按天来回滚,则最大保存时间为1天,1天之前的都将被清理掉 -->
15             <maxHistory>30</maxHistory>
16         </rollingPolicy>
17         <!-- 日志输出格式 -->
18         <layout class="ch.qos.logback.classic.PatternLayout">
19             <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n</Pattern>
20         </layout>
21     </appender>
22     <!-- 异步输出 -->
23     <!--输出文件-->
24     <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
25         <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
26         <discardingThreshold>0</discardingThreshold>
27         <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
28         <queueSize>512</queueSize>
29         <!-- 添加附加的appender,最多只能添加一个 -->
30         <appender-ref ref="FILE"/>
31     </appender>
32     <!--输出控制台-->
33     <appender name="ASYNC_STD" class="ch.qos.logback.classic.AsyncAppender">
34         <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
35         <discardingThreshold>0</discardingThreshold>
36         <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
37         <queueSize>512</queueSize>
38         <!-- 添加附加的appender,最多只能添加一个 -->
39         <appender-ref ref="STDOUT"/>
40     </appender>
41
42     <root level="DEBUG">
43         <!-- 输出到控制台 -->
44            <appender-ref ref="ASYNC_STD"/>
45            <!-- 输出到文件 -->
46            <!-- <appender-ref ref="ASYNC"/> -->
47     </root>
48
49 </configuration>

github地址:https://github.com/1053531172/springboot2

参考:http://www.ityouknow.com/springboot/2016/11/25/spring-boot-multi-mybatis.html

原文地址:https://www.cnblogs.com/cdblogs/p/9275883.html

时间: 2024-10-30 16:40:18

springboot2.0+mybatis多数据源集成的相关文章

springboot2.0动态多数据源切换

摘要:springboot1.x到springboot2.0配置变化有一点变化,网上关于springboot2.0配置多数据源的资料也比较少,为了让大家配置多数据源从springboot1.x升级到springboot2.0少踩写坑,博主在此介绍用springboot2.0来进行动态数据源切换.(在博客的最后会给大家提供源码的下载地址) 一.引入依赖 <?xml version="1.0" encoding="UTF-8"?> <project x

SpringBoot2 + Druid + Mybatis 多数据源配置

在大数据高并发的应用场景下,为了更快的响应用户请求,读写分离是比较常见的应对方案.读写分离会使用多数据源的使用.下面记录如何搭建SpringBoot2 + Druid + Mybatis  多数据源配置以及在使用过程遇到的问题. 一.先从pom.xml入手(使用springboot 2的版本) <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starte

SpringBoot2.0之八 多数据源配置

 在开发的过程中我们可能都会遇到对接公司其他系统等需求,对于外部的系统可以采用接口对接的方式,对于一个公司开发的两个系统,并且知道相关数据库结构的情况下,就可以考虑使用多数据源来解决这个问题.SpringBoot为我们提供了相对简单的实现. 一.建立如下结构的maven项目 二.添加相关数据库配置信息 server: port: 8080 spring: datasource: master: driver-class-name: com.mysql.jdbc.Driver url: jdbc:

springboot2.0+mybatis+postgresql9.6+quartz(修正版)

做了一个简单的定时任务. 一.依赖 <dependencies> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> --> <dependency> <groupId>org.post

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

一.Mybatis框架 1.mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型.接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录. 2.mybatis特点 1)sql语句与代码分离,存放于xml配置文件中,方便管理 2)用逻辑标签

SpringBoot2.0集成FastDFS

SpringBoot2.0集成FastDFS 前两篇整体上介绍了通过 Nginx 和 FastDFS 的整合来实现文件服务器.但是,在实际开发中对图片或文件的操作都是通过应用程序来完成的,因此,本篇将介绍 Spring Boot 整合 FastDFS 客户端来实现对图片/文件服务器的访问. 如果有不了解 FastDFS 的读者可以先浏览<CentOS7 安装FastDFS分布式文件系统>或是另行查阅网上相关资料. 一.整合编码 项目整体的代码结构图如下: 添加依赖 <project xm

关于springboot2.0与activiti6.0.0集成的问题

spring boot2.0与activiti6.0集成后不能直接使用,会抛出如下异常 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMv

springboot2.0.3使用jpa和hibernate的方式配置多数据源(sqlite和mysql)

application.properties配置: #数据库配置 mysql.spring.datasource.jdbc-url =jdbc:mysql://127.0.0.1:3306/test mysql.spring.datasource.username=admin mysql.spring.datasource.password=123456 mysql.spring.datasource.driver-class-name=com.mysql.jdbc.Driver #数据库连接池

SpringBoot2.0之四 简单整合MyBatis

从最开始的SSH(Struts+Spring+Hibernate),到后来的SMM(SpringMVC+Spring+MyBatis),到目前的S(SpringBoot),随着框架的不断更新换代,也为我们广大的程序猿提供了更多的方便,一起搭建一个从控制层到持久层的项目可能需要一两天的时间,但是采用SpringBoot的方式,我们可能只需要10分钟就能轻松完成一个web项目的搭建,下面我们介绍一下SpringBoot2.0整合MyBatis的方法 一.新建一个项目,引入相关依赖 <!-- 单元测试