springboot

SpringBoot整合JPA的多数据源如何配置

小樊
188
2024-06-14 15:12:47
栏目: 编程语言

在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 实例来操作不同的数据源。

0
看了该问题的人还看了