一、环境准备
新建一个Spring Boot项目,然后在pom.xml中引入相关依赖
mysql
mysql-connector-java
com.microsoft.sqlserver
mssql-jdbc
6.5.4.jre8-preview
test
com.microsoft.sqlserver
sqljdbc4
4.0
org.aspectj
aspectjweaver
1.9.2
二、数据源配置
本文用到的两个数据源分别是MySQL数据库和SqlServer数据库,其中MySQL数据库为主数据库(可自行更改)
spring:
datasource:
##配置主数据库
primary:
jdbc-url: jdbc:mysql://xx.x.x.xxx:3306/quality?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
username: xxx
password: xxx
driver-class-name: com.mysql.cj.jdbc.Driver
##配置次数据库
secondary:
jdbc-url: jdbc:sqlserver://xxx.xxx.xxx.x:1433;DatabaseName=quality
username: sa
password: xxx
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
三、创建数据源配置类
完成数据源的配置后,需创建数据源的配置类;其作用是帮助项目区分spring.datasource.primary和secondary。
第一个配置类:
package com.chinameyer.qualitymanagementsystem.config;
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 javax.s