Configure Multiple Datasources In Spring Boot JdbcTemplate

Configure Multiple Datasources In Spring Boot JdbcTemplate

In this article I’m going to explain how to use multiple datasorces when using the JdbcTemplate and how to confgure transaction management with this setup.

Dependencies

You need to have a spring boot project configured and following dependencies in it. Other than this you will need to define your datasource driver dependencies.

Property file configuration

Here I’m using YML formatted property file to define datasource properties. We are using 2 seperate oracle and postgresql datasources. As you can see oracle datasorce is named “foo” and postgresql datasource is named “bar”.

Bean configuration

After defining datasource properties we need to configure spring to use them as follows. Here I’ve created two bean configuration files for each datasorce.

Let’s go through each step of configuration and see what’s happening here. I’m taking “bar” datasource as an example.

  1. First DataSourceProperties bean has created to get the properties defined in application.yml. You can see the usage of @ConfigurationProperties("spring.bar") in getting the respective datasource we want. Also bean has been named with a qualifier “barProperties” in order to differenciate with other datasource properties we may define.
  2. Then a DataSource bean defined by injecting the DataSourceProperties we created earlier. Here HikariDataSource.class has been used. But you can you the respective driver datasouce classes if you want.
  3. In third step a JdbcTemplate is defined by injecting the DataSource in step two. We can use this JdbcTemplate by autowiring when needed with the defined Qualifier.
  4. Finally a PlatformTransactionManager bean has been created by injecting the DataSource defined in step two in order to handle the transactions in the particular datasource.

At this point we can use the JdbcTemplate as follows

But right now transactions are handled seperately for each datasource and rollback strategies won’t affect each other. In order to fix this problem we need to ChainedTransactionManager and inject the PlatformTransactionManager beans we created in step 04 and make it the primary TransactionManager . We can do it as follows.

Once this configuration is added transactions will be handled across the datasources.

Hope you got something.

Thank you for taking time to read this.

Leave a Comment

%d bloggers like this: