在Spring Boot項目中整合JPA的多數據源,需要配置多個數據源和EntityManagerFactory,并指定哪個數據源對應哪個EntityManagerFactory。
以下是一個簡單的示例配置:
1、application.properties 配置文件中配置兩個數據源的連接信息:
```
# 第一個數據源
spring.datasource.datasource1.url=jdbc:mysql://localhost:3306/database1
spring.datasource.datasource1.username=username1
spring.datasource.datasource1.password=password1
spring.datasource.datasource1.driver-class-name=com.mysql.cj.jdbc.Driver
# 第二個數據源
spring.datasource.datasource2.url=jdbc:mysql://localhost:3306/database2
spring.datasource.datasource2.username=username2
spring.datasource.datasource2.password=password2
spring.datasource.datasource2.driver-class-name=com.mysql.cj.jdbc.Driver
```
2、創建兩個數據源的配置類,分別配置兩個DataSource和EntityManagerFactory:
```java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = "com.example.repository.datasource1",
entityManagerFactoryRef = "entityManagerFactory1",
transactionManagerRef = "transactionManager1"
)
public class DataSource1Config {
@Primary
@Bean(name = "dataSource1")
@ConfigurationProperties(prefix = "spring.datasource.datasource1")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "entityManagerFactory1")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource1") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.entity.datasource1")
.persistenceUnit("datasource1")
.build();
}
@Primary
@Bean(name = "transactionManager1")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory1") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
```
```java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = "com.example.repository.datasource2",
entityManagerFactoryRef = "entityManagerFactory2",
transactionManagerRef = "transactionManager2"
)
public class DataSource2Config {
@Bean(name = "dataSource2")
@ConfigurationProperties(prefix = "spring.datasource.datasource2")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "entityManagerFactory2")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource2") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.entity.datasource2")
.persistenceUnit("datasource2")
.build();
}
@Bean(name = "transactionManager2")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory2") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
```
通過以上配置,就可以實現在Spring Boot項目中整合JPA的多數據源。在使用時,可以通過 @Autowired 注入不同的 EntityManager 實例來操作不同的數據源。