Springboot2.xJpa——详细的多数据源配置和使⽤案例
⽂章⽬录
前⾔
最近有个需求,要同时操作多个数据源,并分别进⾏curd操作。于是百度了⼀番,编写依赖测试demo,搞定了这个问题。以下demo实现功能是:
在数据源⼀中,给测试表新增⼀条数据。
同时在数据源⼆中,给测试表新增数据。
⼀、准备阶段
1.数据表和存储过程
1.1 数据源⼀
-- Create table
create table TEST_DATA
(
id  NUMBER,
name VARCHAR2(30)
)
tablespace PUSH
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
1.2 数据源⼆
-- Create table
create table TEST_JPA
(
id  NUMBER not null,
name VARCHAR2(300)
)
tablespace TBS_BSS_NHIS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-
- Add comments to the columns
comment on column TEST_JPA.id
is 'id';
⼆、集成配置
1.引⼊依赖
compile group: 'org.projectlombok', name: 'lombok', version: '1.18.10'
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.10'    compile 'org.springframework.boot:spring-boot-starter-web'
compile group: 'org.springframework.boot' ,name: 'spring-boot-starter-aop'
compile group: 'org.springframework.boot' ,name: 'spring-boot-starter-data-jpa'
compile 'acle:ojdbc6:11.2.0.3'
compile 'com.alibaba:druid-spring-boot-starter:1.1.20'
compile group: 'org.apachemons' ,name: 'commons-lang3'
compile group: 'com.alibaba', name: 'fastjson', version: '1.2.68'
testCompile group: 'org.springframework.boot',name: 'spring-boot-starter-test'
testCompile group: 'junit', name: 'junit', version: '4.12'
2.设置l
spring:
datasource:
driverClassName: oracle.jdbc.driver.OracleDriver
# 使⽤ alibaba druid 连接池、监控
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 数据源⼀
primary :
url: jdbc:oracle:thin:@x:port:cfc
username: xxx
password: xx
# 数据源⼆
secondary :
url: jdbc:oracle:thin:@x:port:cfc
username: xxx
password: xx
initial-size:2
min-idle:5
max-active:10
max-wait:5000
validation-query: SELECT 1
test-on-borrow:false
test-while-idle:true
time-between-eviction-runs-millis:18800
web-stat-filter:
enabled:true
exclusions: js,gif,jpg,png,css,ico,/druid/*
#      stat-view-servlet:
#        enabled: true
#        login-username: root
#        login-password: druid2019
3.1 DataSourceConfig.java
@Configuration
public class DataSourceConfig {
private static final Logger log = org.Logger(DataSourceConfig.class); /**
* 数据源⼀
* 标红为yml⽂件中数据源路径:primary
*/
@Primary
@Bean(value ="primaryDataSource",initMethod ="init")
@ConfigurationProperties("spring.datasource.druid.primary")
public DataSource dataSourceOne(){
log.info("Init DataSourceOne");
ate().build();
}
/**
* 数据源⼆
* 标红为yml⽂件中数据源路径:secondary
*/
@Bean(value ="secondDataSource",initMethod ="init")
@ConfigurationProperties("spring.datasource.druid.secondary")
public DataSource dataSourceTwo(){
log.info("Init DataSourceTwo");
ate().build();
}
}
3.2.PrimaryJpaConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef ="entityManagerFactoryPrimary",
transactionManagerRef ="transactionManagerPrimary",
//设置Repository所在位置-设置扫包范围
basePackages ={"dao.first.mapper"})
public class PrimaryJpaConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
private HibernateProperties hibernateProperties;
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name ="entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder){
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name ="entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder){ return builder
// 设置数据源
.dataSource(primaryDataSource)
// 设置jpa配置
springboot aop.Properties())
// 设置hibernate配置
.properties(getVendorProperties())
//设置实体类所在位置
.packages("del")
// 设置持久化单元名,⽤于@PersistenceContext注解获取EntityManager时指定数据源
.persistenceUnit("primaryPersistenceUnit")
.build();
}
private Map getVendorProperties(){
return hibernateProperties.Properties(),new HibernateSettings()); }
@Primary
@Bean(name ="transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder){
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
3.3.SecondJpaConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef ="entityManagerFactorySecond",
transactionManagerRef ="transactionManagerSecond",
//设置Repository所在位置-设置扫包范围
basePackages ={"dao.second.mapper"})
public class SecondJpaConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
private HibernateProperties hibernateProperties;
@Autowired
@Qualifier("secondDataSource")
private DataSource secondDataSource;
@Bean(name ="secondEntityManager")
public EntityManager entityManager(EntityManagerFactoryBuilder builder){
return entityManagerFactorySecond(builder).getObject().createEntityManager();
}
@Bean(name ="entityManagerFactorySecond")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond(EntityManagerFactoryBuilder builder){ return builder
.dataSource(secondDataSource)
// 设置jpa配置
.Properties())
.properties(getVendorProperties())
//设置实体类所在位置
.packages("del")
.persistenceUnit("secondPersistenceUnit")
.build();
}
private Map getVendorProperties(){
return hibernateProperties.Properties(),new HibernateSettings()); }
@Bean(name ="transactionManagerSecond")
public PlatformTransactionManager transactionManagerSecond(EntityManagerFactoryBuilder builder){
return new JpaTransactionManager(entityManagerFactorySecond(builder).getObject());
}
}
4. 定义实体和映射
包路径:dao.first
4.1 TestDataModel.java