在Spring Boot中为不同的DataSources配置JPA仓库,可以通过以下步骤实现:
# 第一个数据源
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=user1
spring.datasource.password=password1
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 第二个数据源
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2
spring.datasource.secondary.username=user2
spring.datasource.secondary.password=password2
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
@Configuration
@EnableJpaRepositories(basePackages = "com.example.repository", entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager")
public class DataSourceConfig {
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("dataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.example.entity").build();
}
@Primary
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
@Configuration
@EnableJpaRepositories(basePackages = "com.example.secondary.repository", entityManagerFactoryRef = "secondaryEntityManagerFactory", transactionManagerRef = "secondaryTransactionManager")
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 secondaryDataSource) {
return builder.dataSource(secondaryDataSource).packages("com.example.secondary.entity").build();
}
@Bean(name = "secondaryTransactionManager")
public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory secondaryEntityManagerFactory) {
return new JpaTransactionManager(secondaryEntityManagerFactory);
}
}
@SpringBootApplication
@Import({DataSourceConfig.class, SecondaryDataSourceConfig.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
通过以上步骤,就可以在Spring Boot中为不同的DataSources配置JPA仓库。在使用JPA时,可以通过@Qualifier
注解指定使用哪个数据源。同时,根据具体业务需求,可以使用不同的JPA Repository接口进行数据访问操作。
注意:以上示例中的代码仅供参考,实际应用中可能需要根据具体情况进行调整。
领取专属 10元无门槛券
手把手带您无忧上云