前言
这里展示的是springBoot项目双数据源的配置,为了增加一定的代表性,这里采用两个不同的数据库Orcale和Mysql作为数据源。
依赖
<!-- orcale驱动包 -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<!-- JDBC:mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
<scope>runtime</scope>
</dependency>
<!--德鲁伊,数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!-- Mybatis_plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis.plus.version}</version>
<exclusions>
<exclusion>
<artifactId>jsqlparser</artifactId>
<groupId>com.github.jsqlparser</groupId>
</exclusion>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
目录结构
操作实体类
person
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
public class Person {
private Integer id;
private String name;
private Integer age;
private String parentName;
public Person() {
}
public Person(String name, Integer age, String parentName) {
this.name = name;
this.age = age;
this.parentName = parentName;
}
}
数据源配置
application.properties
# 配置orcale的相关连接信息
orcale.dataSource.type= oracle.jdbc.datasource.impl.OracleConnectionPoolDataSource
orcale.dataSource.url = jdbc:oracle:thin:@localhost:1521:orcl?Unicode=true&characterEncoding=UTF-8&useSSL=false
orcale.dataSource.driverClassName = oracle.jdbc.driver.OracleDriver
orcale.dataSource.username = testrole
orcale.dataSource.password = 123456
orcale.dataSource.druid.max-active = 20
orcale.dataSource.druid.initial-size = 20
orcale.dataSource.druid.max-wait = 3000
orcale.dataSource.druid.minIdle = 10
orcale.dataSource.druid.time-between-eviction-runsMillis = 60000
orcale.dataSource.druid.min-evictable-idle-timeMillis = 300000
orcale.dataSource.druid.validation-query = SELECT 1
orcale.dataSource.druid.test-while-idle = true
orcale.dataSource.druid.test-on-borrow = false
orcale.dataSource.druid.test-on-return = false
orcale.dataSource.druid.pool-prepared-statements = false
orcale.dataSource.druid.max-open-prepared-statements = -1
# 配置mysql中的的相关配置
mysql.dataSource.type =com.mysql.cj.jdbc.MysqlDataSource
mysql.dataSource.url = jdbc:mysql://localhost:3306/xmltest?useUnicode=true&characterEncoding=UTF-8&useSSL=false
mysql.dataSource.driverClassName = com.mysql.cj.jdbc.Driver
mysql.dataSource.username = root
mysql.dataSource.password = shijian
mysql.dataSource.druid.max-active = 40
mysql.dataSource.druid.initial-size = 40
mysql.dataSource.druid.max-wait = 3000
mysql.dataSource.druid.minIdle = 20
mysql.dataSource.druid.time-between-eviction-runsMillis = 60000
mysql.dataSource.druid.min-evictable-idle-timeMillis = 300000
mysql.dataSource.druid.validation-query = SELECT 1
mysql.dataSource.druid.test-while-idle = true
mysql.dataSource.druid.test-on-borrow = false
mysql.dataSource.druid.test-on-return = false
mysql.dataSource.druid.pool-prepared-statements = false
mysql.dataSource.druid.max-open-prepared-statements = -1
映射文件
Mysql
mysqlPersonMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.summary.dao.MysqlPersonMapper">
<select id="getAll" resultType="com.example.summary.util.Person">
SELECT * FROM person
</select>
</mapper>
Orcale
orcalePersonMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.summary.dao.OrcalePersonMapper">
<select id="getAll" resultType="com.example.summary.util.Person">
SELECT * FROM person
</select>
</mapper>
mapper
import com.example.summary.util.Person;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface MysqlPersonMapper {
List<Person> getAll();
}
import com.example.summary.util.Person;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface OrcalePersonMapper {
List<Person> getAll();
}
注
mapper不能放在一个包内不然就只会让主数据源识别到,其它源无法识别
配置注入
Mysql
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
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 org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.example.summary.mysql",sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MysqlDataSourceConfig {
// 读取配置文件中的 spring.datasource配置
// 配置多数据源时要默认一个数据源,所以要加 @Primary
@ConfigurationProperties(prefix = "mysql.datasource")
@Bean(name = "mysqlDataSource")
@Primary
public DataSource dataSource() {
return new DruidDataSource();
}
@Bean(name = "mysqlTransactionManager")
@Primary
public DataSourceTransactionManager mysqlTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean(name = "mysqlSqlSessionFactory")
@Primary
public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource mysqlDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(mysqlDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/mysql/*.xml")); // 对应的mapper.xml
//mybatis 数据库字段与实体类属性驼峰映射配置
sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return sessionFactory.getObject();
}
@Bean(name = "mysqlJdbcTemplate")
@Primary
public JdbcTemplate mysqlJdbcTemplate() {
return new JdbcTemplate(dataSource());
}
}
Orcale
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
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 org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.example.summary.orcale",sqlSessionFactoryRef = "orcaleSqlSessionFactory")
public class OrcaleDataSourceConfig {
@ConfigurationProperties(prefix = "orcale.datasource")
@Bean(name = "orcaleDataSource")
public DataSource dataSource() {
return new DruidDataSource();
}
@Bean(name = "orcaleTransactionManager")
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean(name = "orcaleSqlSessionFactory")
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("orcaleDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/orcale/*.xml")); // 对应的mapper.xml
//mybatis 数据库字段与实体类属性驼峰映射配置
sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return sessionFactory.getObject();
}
@Bean(name = "orcaleJdbcTemplate")
public JdbcTemplate orcaleJdbcTemplate() {
return new JdbcTemplate(dataSource());
}
}
注
@Primary注解代表该数据源为主数据源
@MapperScan的basePackages值代表的是包扫描位置,及该包下的所有mapper都会被扫描且绑定在数据源上
测试
元数据
Mysql
Orcale
测试代码
import com.example.summary.mysql.MysqlPersonMapper;
import com.example.summary.orcale.OrcalePersonMapper;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@MapperScan(value = "com.example.summary.dao")
public class test {
@Autowired
MysqlPersonMapper mysqlPersonMapper;
@Autowired
OrcalePersonMapper orcalePersonMapper;
@Test
public void listAll(){
System.out.println("MySQL数据库--------------");
System.out.println(mysqlPersonMapper.getAll());
System.out.println("Orcale数据库-------------");
System.out.println(orcalePersonMapper.getAll());
}
}