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.
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”.
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.
DataSourcePropertiesbean 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.
- Then a
DataSourcebean defined by injecting the
DataSourcePropertieswe created earlier. Here
HikariDataSource.classhas been used. But you can you the respective driver datasouce classes if you want.
- In third step a
JdbcTemplateis defined by injecting the
DataSourcein step two. We can use this
JdbcTemplateby autowiring when needed with the defined Qualifier.
- Finally a
PlatformTransactionManagerbean has been created by injecting the
DataSourcedefined 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.