前言
因为项目要求需要两个项目中同时使用3个数据源,然后就折腾了一下。从网上也看了许多的案例,但是都多多少少有问题。比如说MyBatis只能用注解开发,而不能用配置之类的。这个我觉得无坑版吧,尽量会说的详细一点。
目录结构
主要依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- 分页插件,尝试高版本和spring-boot-starter-pagehalper 均启动失败 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
在 pom.xml的<build>
标签中添加静态资源扫描:
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
配置文件
application.yml 配置
主要给出数据源的配置
spring:
datasource:
pigxpf:
type: com.alibaba.druid.pool.DruidDataSource
# 注意在配置多数据源时这里要用 jdbc-url,驱动名需要用 driver-class-name
jdbc-url: jdbc:mysql://localhost:3306/pf?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
pigxhr:
type: com.alibaba.druid.pool.DruidDataSource
jdbc-url: jdbc:mysql://localhost:3306/hr?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
# mybatis配置都在 resources/mybatis/mabatis-config.xml中,这里配置并不会自动扫描。
mybatis:
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
mybatis-config配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties>
<property name="dialect" value="mysql" />
</properties>
<settings>
<!-- 开启驼峰匹配 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true,设置只是为了展示出来 -->
<setting name="cacheEnabled" value="true" />
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true,设置只是为了展示出来 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true,设置只是为了展示出来 -->
<setting name="multipleResultSetsEnabled" value="true" />
<!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true,设置只是为了展示出来 -->
<setting name="useColumnLabel" value="true" />
<!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如
Derby)。 系统默认值是false,设置只是为了展示出来 -->
<setting name="useGeneratedKeys" value="false" />
<!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE,设置只是为了展示出来 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null,设置只是为了展示出来 -->
<setting name="defaultStatementTimeout" value="25000" />
</settings>
<!-- 分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 数据库方言 -->
<property name="dialect" value="mysql" />
<property name="offsetAsPageNum" value="true" />
<!-- 设置为true时,使用RowBounds分页会进行count查询 会去查询出总数 -->
<property name="rowBoundsWithCount" value="true" />
<property name="pageSizeZero" value="true" />
<property name="reasonable" value="true" />
</plugin>
</plugins>
</configuration>
Application.java启动类
我这里什么都没动也能正常用,有的博客说要取消自动扫描,因为自动扫描只会加载一个数据源。
配置类
DataSourceConfig.java
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.sql.DataSource;
/**
* @author: litblue
* @Time : 2019/7/28 10:38
* @Email: litblue@163.com
* 绝不敷衍,毫不懈怠
*
* 手动配置数据源
*
*/
@Configuration
public class DataSourceConfig {
@Bean(name = "pigxpfDatasource")
@Primary /* 主要数据源 */
@ConfigurationProperties(prefix = "spring.datasource.pigxpf")
public DataSource pigxpfDatasource(){
return DataSourceBuilder.create().build();
}
@Bean(name = "pigxhrDatasource")
@ConfigurationProperties(prefix = "spring.datasource.pigxhr")
public DataSource pighrDatasource(){
return DataSourceBuilder.create().build();
}
}
MyBatisPigxpfConfig.java
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
* @author: litblue
* @Time : 2019/7/28 10:53
* @Email: litblue@163.com
* 绝不敷衍,毫不懈怠
*/
@Configuration
@MapperScan(basePackages = {"com.pigx.pigxpf.mapper"},sqlSessionFactoryRef = "pigxpfSqlFactory")
public class MyBatisPigxpfConfig {
@Autowired
@Qualifier("pigxpfDatasource")
private DataSource pigxpfSource;
// 加载配置文件
@Value("${mybatis.configLocation}")
private String configLocation;
@Bean(name="pigxpfSqlFactory")
@Primary
public SqlSessionFactory pigxpfSqlSessionFactory() throws Exception{
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(pigxpfSource);
// 配置类型别名
factoryBean.setTypeAliasesPackage("com.pigx.pigxpf.entity");
// 配置mapper的扫描,找到所有的mapper.xml映射文件
Resource[] resources = new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/*.xml");
factoryBean.setMapperLocations(resources);
// 加载配置文件
factoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
return factoryBean.getObject();
}
@Bean(name="pigxpfSqlFactory")
@Primary
public SqlSessionTemplate pigxpfSqlSessionTemplate() throws Exception{
SqlSessionTemplate template = new SqlSessionTemplate(pigxpfSqlSessionFactory());
return template;
}
}
MyBatisPigxhrConfig.java
这里与上述相同,只是不需要添加@Primary 注解了。
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
* @author: litblue
* @Time : 2019/7/28 11:26
* @Email: litblue@163.com
* 绝不敷衍,毫不懈怠
*/
@Configuration
@MapperScan(basePackages = {"com.pigx.pigxpf.mapper"},sqlSessionFactoryRef = "pigxpfSqlFactory")
public class MyBatisPigxhrConfig {
@Autowired
@Qualifier("pigxhrDatasource")
private DataSource pigxhrSource;
@Value("${mybatis.configLocation}")
private String configLocation;
@Bean(name="pigxhrSqlFactory")
public SqlSessionFactory pigxhrSqlSessionFactory() throws Exception{
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(pigxhrSource);
// 配置类型别名
factoryBean.setTypeAliasesPackage("com.pigx.pigxpf.entity");
// 配置mapper的扫描,找到所有的mapper.xml映射文件
Resource[] resources = new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/*.xml");
factoryBean.setMapperLocations(resources);
// 加载配置文件
factoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
return factoryBean.getObject();
}
@Bean(name="pigxhrSqlFactory")
public SqlSessionTemplate pigxhrSqlSessionTemplate() throws Exception{
SqlSessionTemplate template = new SqlSessionTemplate(pigxhrSqlSessionFactory());
return template;
}
}
运行结果
最后
关于Druid 的监控的暂时还没有配置,也还不知道咋弄,过段时间再更新。