开发环境:JDK1.8+SpringBoot2.4.12+Oracle
这里我们假设要使用两个数据源分别为:master和slave。
- pom.xml 依赖包
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-jpa
com.github.noraui
ojdbc7
12.1.0.2
org.apache.commons
commons-lang3
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
- application.yml配置
server:
port: 50000
---
spring:
jpa:
hibernate:
ddlAuto: update
openInView: true
showSql: false
databasePlatform: org.hibernate.dialect.Oracle10gDialect
---
# 第一个数据源
master:
datasource:
driverClassName: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@localhost:1521/orcl
username: t0
password: t0
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimumIdle: 10
maximumPoolSize: 200
autoCommit: true
idleTimeout: 30000
poolName: MasterDatabookHikariCP
maxLifetime: 1800000
connectionTimeout: 30000
connectionTestQuery: SELECT 1 FROM DUAL
# 第二个数据源
slave:
datasource:
driverClassName: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@localhost:1521/orcl
username: t1
password: t1
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimumIdle: 10
maximumPoolSize: 200
autoCommit: true
idleTimeout: 30000
poolName: SlaveDatabookHikariCP
maxLifetime: 1800000
connectionTimeout: 30000
connectionTestQuery: SELECT 1 FROM DUAL
---
# mybatis 配置,分表对应到不同的包中
master:
mybatis:
config-location: classpath:/MyBatis-conf.xml
type-aliases-package: com.pack.domain #master数据源对应的包
mapper-locations:
- classpath:/com/pack/mapper/oracle/*.xml #master数据源对应mapper文件
slave:
mybatis:
config-location: classpath:/MyBatis-conf.xml
type-aliases-package: com.pack.slave.domain #slave数据源对应的包
mapper-locations:
- classpath:/com/pack/slave/mapper/oracle/*.xml #slave数据源对应mapper文件
---
# jpa相关的配置
master:
jpa:
repos: com.pack.base.repository #master数据源对应的包配置
domain: com.pack.domain #master对应的实体包
slave:
jpa:
repos: com.pack.slave.repository #salve数据源对应的包配置
domain: com.pack.slave.domain #slave对应的实体包
以上就是两个数据源对应相关的配置了,大家注意看里面的注释。接下来我们看mabatis和jpa对应的类相关的配置了,都是固定的配置。
- 数据源属性配置对应的java类配置
BaseProperties类
public class BaseDataSourceProperties implements BeanClassLoaderAware, InitializingBean {
private ClassLoader classLoader;
private String name;
private boolean generateUniqueName;
private Class initializeDataSourceBuilder() {
return DataSourceBuilder.create(getClassLoader()).type(getType())
.driverClassName(determineDriverClassName()).url(determineUrl())
.username(determineUsername()).password(determinePassword());
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGenerateUniqueName() {
return this.generateUniqueName;
}
public void setGenerateUniqueName(boolean generateUniqueName) {
this.generateUniqueName = generateUniqueName;
}
public Class