使用 @EnableAutoConfiguration 和 application.properties:
示例 application.properties:
# Primary Data Source spring.datasource.url=jdbc:h2:mem:default spring.datasource.username=sa spring.datasource.password= # Additional Data Source additional.datasource.url=jdbc:h2:mem:additional additional.datasource.username=anotheruser additional.datasource.password=anotherpassword
示例配置类主要数据源:
<code class="java">@Configuration @EnableTransactionManagement @EnableAutoConfiguration @EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager", basePackages = {"com.example.repository.primary"}) public class PrimaryDataSourceConfig { @Bean public EntityManagerFactory entityManagerFactory() { // Create and configure EntityManagerFactory manually } @Bean public PlatformTransactionManager transactionManager() { // Create and configure PlatformTransactionManager manually } }</code>
其他数据源的示例配置类:
<code class="java">@Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "additionalEntityManagerFactory", transactionManagerRef = "additionalTransactionManager", basePackages = {"com.example.repository.additional"}) public class AdditionalDataSourceConfig { @Value("${additional.datasource.url}") private String url; @Value("${additional.datasource.username}") private String username; @Value("${additional.datasource.password}") private String password; @Bean public DataSource additionalDataSource() { // Create and configure DataSource manually } @Bean public EntityManagerFactory additionalEntityManagerFactory() { // Create and configure EntityManagerFactory manually } @Bean public PlatformTransactionManager additionalTransactionManager() { // Create and configure PlatformTransactionManager manually } }</code>
具有事务注释的示例服务类:
<code class="java">@Service @Transactional("transactionManager") // Use primary transaction manager public class PrimaryService { // ... } @Service @Transactional("additionalTransactionManager") // Use additional transaction manager public class AdditionalService { // ... }</code>
在 Spring Boot 应用程序中处理多个数据源时,这种方法提供了更好的控制和灵活性。
以上是如何通过 Spring Data JPA 在 Spring Boot 中配置和使用多个数据源?的详细内容。更多信息请关注PHP中文网其他相关文章!