不同数据库类型以Oracle 和 MySQL 为例
项目创建
创建SpringBoot项目,就不赘述了,IntelliJ IDEA的 spring initializr 、start.spring.io网站 等方式都可以快速创建一个SpringBoot项目。tips:持久层使用的MyBatis
项目配置
pom 文件(spring-boot-starter-parent 版本为1.5.16)
<properties>
<java.version>1.8</java.version>
<com.oracle.version>11.2.0.1.0</com.oracle.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>${com.oracle.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--slf4j依赖-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!--MyBatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!-- mybatis连接oracle报错所导入 -->
<dependency>
<groupId>cn.easyproject</groupId>
<artifactId>orai18n</artifactId>
<version>12.1.0.2.0</version>
</dependency>
<!--druid連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
3.application文件
server:
port:8090
#双数据源配置
spring:
datasource:
mysql:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull&serverTimezone=UTC&rewriteBatchedStatements=true&relaxAutoCommit=true&useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
initial-size: 5
min-idle: 5
max-active: 20
# 连接等待超时时间
max-wait: 60000
# 间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 一个连接在池中最小生存时间,单位是毫秒
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
#oracle数据源配置
oracle:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@localhost:1521/orcl
username: tizer
password: tizer
type: com.alibaba.druid.pool.DruidDataSource
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
配置文件
主数据源mysql
package top.tizer.doubledatasource.config;
import com.alibaba.druid.pool.DruidDataSource;
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.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
/**
* @Moudle MysqlMybatisConfig.java
*
* @author 桃子dev
*
* @email
*
* Created by 2019/11/21 16:56
*
* @description mysql数据库配置
**/
@Configuration
@MapperScan(basePackages = {"top.tizer.doubledatasource.mapper.mysql"},sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MysqlMybatisConfig {
@Value("${spring.datasource.mysql.filters}")
private String filters;
@Value("${spring.datasource.mysql.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.mysql.username}")
private String username;
@Value("${spring.datasource.mysql.password}")
private String password;
@Value("${spring.datasource.mysql.url}")
private String url;
@Value("${spring.datasource.mysql.initial-size}")
private int initialSize;
@Value("${spring.datasource.mysql.max-active}")
private int maxActive;
@Value("${spring.datasource.mysql.min-idle}")
private int minIdle;
@Value("${spring.datasource.mysql.max-wait}")
private long maxWait;
@Value("${spring.datasource.mysql.time-between-eviction-runs-millis}")
private long timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.mysql.min-evictable-idle-time-millis}")
private long minEvictableIdleTimeMillis;
@Value("${spring.datasource.mysql.validation-query}")
private String validationQuery;
@Value("${spring.datasource.mysql.test-while-idle}")
private boolean testWhileIdle;
@Value("${spring.datasource.mysql.test-on-borrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.mysql.test-on-return}")
private boolean testOnReturn;
@Bean(name = "mysqlDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.mysql")
public DataSource mysqlDataSource() throws SQLException{
DruidDataSource druid = new DruidDataSource();
druid.setFilters(filters);
druid.setDriverClassName(driverClassName);
druid.setUrl(url);
druid.setUsername(username);
druid.setPassword(password);
druid.setInitialSize(initialSize);
//最大連接池的數量
druid.setMaxActive(maxActive);
//最小连接池数量
druid.setMinIdle(minIdle);
//获取连接时最大等待时间,单位毫秒
druid.setMaxWait(maxWait);
//间隔多久进行一次检测,检测需要关闭的空闲连接
druid.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
//一个连接在池中最小生存时间
druid.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
//用来检测连接是否有效的sql
druid.setValidationQuery(validationQuery);
//建议配置为true,不影响性能,并且保证安全性。
druid.setTestWhileIdle(testWhileIdle);
//申请连接时执行validationQuery 检测连接是否有效
druid.setTestOnBorrow(testOnBorrow);
druid.setTestOnReturn(testOnReturn);
return druid;
}
@Bean(name = "mysqlSqlSessionFactory")
@Primary
public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource mysqlDataSource)
throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(mysqlDataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:top/tizer/doubledatasource/mapper/mysql/*/*Mapper.xml"));
return bean.getObject();
}catch (IOException e){
e.printStackTrace();
throw new RuntimeException();
}
}
@Bean(name = "mysqlSqlSessionTemplate")
@Primary
public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory mysqlSqlSessionFactory){
SqlSessionTemplate template = new SqlSessionTemplate(mysqlSqlSessionFactory);
return template;
}
}
从数据源oracle
package top.tizer.doubledatasource.config;
import com.alibaba.druid.pool.DruidDataSource;
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.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
@Configuration
@MapperScan(basePackages = {"top.tizer.doubledatasource.mapper.oracle"},sqlSessionFactoryRef = "oracleSqlSessionFactory")
public class OracleMybatisConfig {
@Value("${spring.datasource.oracle.filters}")
private String filters;
@Value("${spring.datasource.oracle.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.oracle.username}")
private String username;
@Value("${spring.datasource.oracle.password}")
private String password;
@Value("${spring.datasource.oracle.url}")
private String url;
@Value("${spring.datasource.oracle.initial-size}")
private int initialSize;
@Value("${spring.datasource.oracle.max-active}")
private int maxActive;
@Value("${spring.datasource.oracle.min-idle}")
private int minIdle;
@Value("${spring.datasource.oracle.max-wait}")
private long maxWait;
@Value("${spring.datasource.oracle.time-between-eviction-runs-millis}")
private long timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.oracle.min-evictable-idle-time-millis}")
private long minEvictableIdleTimeMillis;
@Value("${spring.datasource.oracle.validation-query}")
private String validationQuery;
@Value("${spring.datasource.oracle.test-while-idle}")
private boolean testWhileIdle;
@Value("${spring.datasource.oracle.test-on-borrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.oracle.test-on-return}")
private boolean testOnReturn;
@Bean(name = "oracleDataSource")
@ConfigurationProperties(prefix = "spring.datasource.oracle")
public DataSource oracleDataSource() throws SQLException {
DruidDataSource druid = new DruidDataSource();
druid.setFilters(filters);
druid.setDriverClassName(driverClassName);
druid.setUsername(username);
druid.setPassword(password);
druid.setUrl(url);
druid.setTestWhileIdle(testWhileIdle);
druid.setInitialSize(initialSize);
druid.setMaxActive(maxActive);
druid.setMinIdle(minIdle);
druid.setMaxWait(maxWait);
druid.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
druid.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
druid.setValidationQuery(validationQuery);
druid.setTestOnReturn(testOnReturn);
druid.setTestOnBorrow(testOnBorrow);
return druid;
}
@Bean(name = "oracleSqlSessionFactory")
public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("oracleDataSource") DataSource oracleDataSource)
throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(oracleDataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:top/tizer/doubledatasource/mapper/oracle/*/*Mapper.xml"));
return bean.getObject();
}catch (IOException e){
e.printStackTrace();
throw new RuntimeException();
}
}
@Bean(name = "oracleSqlSessionTemplate")
public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("oracleSqlSessionFactory") SqlSessionFactory oracleSqlSessionFactory){
SqlSessionTemplate template = new SqlSessionTemplate(oracleSqlSessionFactory);
return template;
}
}
这样基本复杂的配置就OK了,完整项目见github,数据库表的建表语句就不写了,根据项目中entity包下实体类创建就OK了。