Spring Boot 27:Springboot配置两个数据库,2024年最新flutter页面跳转下一页面后刷新
在Spring Boot中配置两个数据库通常涉及到创建两个或多个数据源以及相应的实体管理器。以下是一个配置两个数据库的示例:
- 在
application.properties
或application.yml
中配置两个数据库的连接信息:
# 数据库1配置
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/db1
spring.datasource.primary.username=root
spring.datasource.primary.password=password
# 数据库2配置
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/db2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=password
- 配置两个数据源:
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
- 配置两个实体管理器:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"com.yourpackage.repository.primary"} // 设置repository所在位置
)
public class PrimaryDataSourceConfig {
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (
EntityManagerFactoryBuilder builder,
@Qualifier("primaryDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.yourpackage.model.primary") // 设置实体类所在位置
.persistenceUnit("primary")
.build();
}
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(
@Qualifier("entityManagerFactoryPrimary") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = {"com.yourpackage.repository.secondary"} // 设置repository所在位置
)
public class SecondaryDataSourc
评论已关闭