DEV Community

Cover image for Mastering Multiple Data Sources with Transaction Management in Spring Boot
Dina Essam
Dina Essam

Posted on

Mastering Multiple Data Sources with Transaction Management in Spring Boot

Greetings, fellow developers! Today, let's embark on a captivating journey into the world of Spring Boot and its remarkable capability to manage two data sources within a single application, all while gracefully handling transactions. ๐Ÿš€

Necessity of Handling Multiple Data Sources and Transactions

In enterprise-grade applications, the need often arises to interact with multiple databases concurrently. This could involve managing critical data across distinct databases while ensuring the integrity and consistency of transactions across these sources.

Configuring Multiple Data Sources and Transaction Management in Spring Boot

Step 1: Defining Data Source Properties

In your application.properties or application.yml, specify the configurations for both data sources:

# Primary Database Configuration
spring.datasource.primary.url=jdbc:mysql://localhost:3306/primarydb
spring.datasource.primary.username=dbuser1
spring.datasource.primary.password=dbpassword1
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver

# Secondary Database Configuration
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondarydb
spring.datasource.secondary.username=dbuser2
spring.datasource.secondary.password=dbpassword2
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver

Enter fullscreen mode Exit fullscreen mode

Step 2: Configuring DataSource Beans

Letโ€™s configure these data sources as beans and enable transaction management:

@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Primary
    @Bean(name = "primaryDataSource")
    @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();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
        return new DataSourceTransactionManager(primaryDataSource);
    }

    @Bean(name = "secondaryTransactionManager")
    public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        return new DataSourceTransactionManager(secondaryDataSource);
    }
}

Enter fullscreen mode Exit fullscreen mode

Utilizing Transactional Operations in Your Spring Boot Application

Now, letโ€™s employ transactional capabilities while interacting with these data sources:

@Service
public class DataService {

    private final JdbcTemplate primaryJdbcTemplate;
    private final JdbcTemplate secondaryJdbcTemplate;

    public DataService(@Qualifier("primaryJdbcTemplate") JdbcTemplate primaryJdbcTemplate,
                       @Qualifier("secondaryJdbcTemplate") JdbcTemplate secondaryJdbcTemplate) {
        this.primaryJdbcTemplate = primaryJdbcTemplate;
        this.secondaryJdbcTemplate = secondaryJdbcTemplate;
    }

    @Transactional("transactionManager")
    public void performTransactionOnPrimaryDatabase() {
        // Perform transactional operations using primaryJdbcTemplate
        primaryJdbcTemplate.update("INSERT INTO table_in_primary VALUES (?, ?)", 1, "Data");
    }

    @Transactional("secondaryTransactionManager")
    public void performTransactionOnSecondaryDatabase() {
        // Perform transactional operations using secondaryJdbcTemplate
        secondaryJdbcTemplate.update("INSERT INTO table_in_secondary VALUES (?, ?)", 2, "More Data");
    }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion:

With Spring Boot's impeccable handling of multiple data sources and its robust transaction management capabilities, you've unlocked the ability to execute transactions across different databases seamlessly. This empowers developers to build resilient and scalable applications, ensuring data integrity while operating across diverse data sources.

Happy coding, and may your Spring Boot applications thrive with flawless data management! ๐ŸŒ๐Ÿ’พ๐Ÿ› ๏ธ

Top comments (2)

Collapse
 
robinamirbahar profile image
Robina

Well-structured, informative, and engaging article

Collapse
 
thilina_madumal profile image
Thilina Madumal

@Qualifier("primaryJdbcTemplate")

It is not mentioned how to create these beans :)