【精·超详细】SpringBoot 配置多个数据源(连接多个数据库)
在Spring Boot中配置多个数据源通常涉及以下步骤:
- 配置数据源属性。
- 创建数据源实例。
- 配置
EntityManagerFactory
和TransactionManager
。 - 配置
@Configuration
类来扫描相应的包以使用正确的实体。
以下是一个配置两个数据源的示例代码:
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource())
.packages("com.yourpackage.model.primary")
.persistenceUnit("primary")
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondaryDataSource())
.packages("com.yourpackage.model.secondary")
.persistenceUnit("secondary")
.build();
}
@Bean
public PlatformTransactionManager primaryTransactionManager(
@Qualifier("primaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
@Bean
public PlatformTransactionManager secondaryTransactionManager(
@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
在application.properties
或application.yml
中配置数据源:
spring.datasource.primary.url=jdbc:mysql://localhost:3306/db_primary
spring.datasource.primary.username=user_primary
spring.datasource.primary.password=pass_primary
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db_secondary
spring.datasource.secondary.username=user_secondary
spring.datasource.secondary.password=pass_secondary
确保为每个数据源创建不同的包路
评论已关闭