Configuring multiple data sources in Spring Boot involves defining multiple DataSource beans and using them with separate EntityManagerFactory and TransactionManager beans. Here's a basic guide on how to set it up:
1. Add DB Dependencies in pom.xml
2.
Application Properties - Define
the data source properties in application.properties
# DataSource 1
spring.datasource1.url=jdbc:mysql://localhost:3306/db1
spring.datasource1.username=user1
spring.datasource1.password=pass1
spring.datasource1.driver-class-name=com.mysql.cj.jdbc.Driver
# DataSource 2
spring.datasource2.url=jdbc:mysql://localhost:3306/db2
spring.datasource2.username=user2
spring.datasource2.password=pass2
spring.datasource2.driver-class-name=com.mysql.cj.jdbc.Driver
3.
Define DataSource Configuration
Classes:Create separate configuration classes for each data
source.
@Configuration
@EnableTransactionManagement
public class DataSourceConfig1 {
@Bean
@ConfigurationProperties(prefix = "spring.datasource1")
public
DataSource dataSource1() {
return
DataSourceBuilder.create().build();
}
@Bean
public
LocalContainerEntityManagerFactoryBean
entityManagerFactory1(EntityManagerFactoryBuilder builder,
@Qualifier("dataSource1") DataSource dataSource) {
return
builder
.dataSource(dataSource)
.packages("com.example.package1") // Specify the package for
entities
.persistenceUnit("db1")
.build();
}
@Bean
public
PlatformTransactionManager transactionManager1(EntityManagerFactory
entityManagerFactory) {
return
new JpaTransactionManager(entityManagerFactory);
}
}
@Configuration
@EnableTransactionManagement
public class DataSourceConfig2 {
@Bean
@ConfigurationProperties(prefix = "spring.datasource2")
public
DataSource dataSource2() {
return
DataSourceBuilder.create().build();
}
@Bean
public
LocalContainerEntityManagerFactoryBean
entityManagerFactory2(EntityManagerFactoryBuilder builder,
@Qualifier("dataSource2") DataSource dataSource) {
return
builder
.dataSource(dataSource)
.packages("com.example.package2") // Specify the package for
entities
.persistenceUnit("db2")
.build();
}
@Bean
public
PlatformTransactionManager transactionManager2(EntityManagerFactory
entityManagerFactory) {
return
new JpaTransactionManager(entityManagerFactory);
}
}
4. Using the DataSources:Specify which data source to use in your repositories by qualifying them with the appropriate @Qualifier or using repository-specific configurations if necessary.
@Repository
@Qualifier("dataSource1")
public interface MyRepository1
extends JpaRepository<MyEntity1, Long> {
}
@Repository
@Qualifier("dataSource2")
public interface MyRepository2
extends JpaRepository<MyEntity2, Long> {
}
With this setup, Spring Boot will configure and connect to multiple data sources based on the provided configuration. The EntityManagerFactory and TransactionManager beans are tailored to each data source, allowing you to manage transactions and entities independently across different databases.
No comments:
Post a Comment