Using @EnableAutoConfiguration and application.properties:
Example 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
Example Configuration Class for Primary Data Source:
<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>
Example Configuration Class for Additional Data Source:
<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>
Example Service Class with Transactional Annotations:
<code class="java">@Service @Transactional("transactionManager") // Use primary transaction manager public class PrimaryService { // ... } @Service @Transactional("additionalTransactionManager") // Use additional transaction manager public class AdditionalService { // ... }</code>
This approach provides greater control and flexibility when working with multiple data sources in Spring Boot applications.
The above is the detailed content of How to Configure and Use Multiple Data Sources in Spring Boot with Spring Data JPA?. For more information, please follow other related articles on the PHP Chinese website!