达梦数据源配置_JPA多源数据库配置(达梦数据库)
时间: 2023-07-27 07:32:17 浏览: 100
好的,下面是达梦数据库的 JPA 多源数据库配置方法:
1. 首先,在 pom.xml 文件中添加达梦数据库的 JDBC 驱动依赖:
```xml
<dependency>
<groupId>dm.jdbc.driver</groupId>
<artifactId>dm7jdbc</artifactId>
<version>7.2.2-jre7</version>
</dependency>
```
2. 在 application.properties 文件中添加数据源的配置信息:
```properties
# 主数据源
spring.datasource.primary.url=jdbc:dm://localhost:5236/mydb
spring.datasource.primary.username=myusername
spring.datasource.primary.password=mypassword
spring.datasource.primary.driver-class-name=dm.jdbc.driver.DmDriver
# 第二个数据源
spring.datasource.secondary.url=jdbc:dm://localhost:5236/mydb2
spring.datasource.secondary.username=myusername2
spring.datasource.secondary.password=mypassword2
spring.datasource.secondary.driver-class-name=dm.jdbc.driver.DmDriver
```
3. 在代码中配置 JPA 的多源数据库:
```java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "primaryEntityManagerFactory",
transactionManagerRef = "primaryTransactionManager",
basePackages = {"com.example.primary.repository"}
)
public class PrimaryDataSourceConfig {
@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "primaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(
EntityManagerFactoryBuilder builder, @Qualifier("primaryDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.primary.entity")
.persistenceUnit("primary")
.build();
}
@Primary
@Bean(name = "primaryTransactionManager")
public PlatformTransactionManager primaryTransactionManager(
@Qualifier("primaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "secondaryEntityManagerFactory",
transactionManagerRef = "secondaryTransactionManager",
basePackages = {"com.example.secondary.repository"}
)
public class SecondaryDataSourceConfig {
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(
EntityManagerFactoryBuilder builder, @Qualifier("secondaryDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.secondary.entity")
.persistenceUnit("secondary")
.build();
}
@Bean(name = "secondaryTransactionManager")
public PlatformTransactionManager secondaryTransactionManager(
@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
```
以上是达梦数据库的 JPA 多源数据库配置方法,希望对你有所帮助。
阅读全文