本篇文章主要介绍SpringBoot框架实现Jpa多源数据库的配置,本次使用国产数据库达梦数据库做为数据源。
1.准备工作
在pom.xml文件中引入Spring Data Jpa依赖:
org.springframework.boot
spring-boot-starter-data-jpa
在application.yml中添加数据库的相关配置:
spring:
datasource:
one:
driver-class-name: dm.jdbc.driver.DmDriver
url: jdbc:dm://127.0.0.1:5236/TESTONE
username: TESTONE
password: 1234567890
type: com.alibaba.druid.pool.DruidDataSource
two:
driver-class-name: dm.jdbc.driver.DmDriver
url: jdbc:dm://127.0.0.1:5237/TESTTWO
username: TESTTWO
password: 1234567890
type: com.alibaba.druid.pool.DruidDataSource
jpa:
properties:
hibernate.dialect: org.hibernate.dialect.Oracle10gDialect
show-sql: ture
编写DataSourceConfig配置文件:
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.one")
@Primary
DataSource dsOne(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.two")
DataSource dsTwo(){
return DruidDataSourceBuilder.create().build();
}
}
2.创建JPA配置
根据配置好的数据源创建两个不同的JPA配置,代码如下(示例):
第一个jpa配置:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "org.xiaoyang.dao1",//持久层路径
entityManagerFactoryRef = "entityManagerFactoryBeanOne",
transactionManagerRef = "platformTransactionManagerOne")
public class JpaConfigOne {
@Resource(name = "dsOne")
DataSource dsOne;
@Autowired
JpaProperties jpaProperties;
@Bean
@Primary
LocalContainerEntityManagerFactoryBean entityManagerF