Adding two database connections to a Spring Boot application is quite straightforward unless you are using JpaRepositories. Simple task of giving JdbcTemplate beans different identifier names becomes a bit confusing.
Starting with the configuration file the only thing needed is having different initials like
These will be used for datasource creation and after that identifiers will be enough to separate JDBC beans.
In a configuration file or in the SpringBoot main class define these datasource beans.
Read configuration information from resources
Create a datasource with a name from that configuration
Set the datasource created to a specific JdbcTemplate. The name given here will be used for accessing to the different JdbcTemplate beans as @Qualifier("jdbcMain") JdbcTemplate jdbcTemplate
While defining a jdbc repository give the identifier for accessing to that database.
What if we want to use JPA and define our objects with Entity. Datasource definitions and initialization will not change. However different EntityManagers and TransactionManagers must be defined.
Annoying part is having auto mapping repositories to these classes is done by scanning packages. Which package to scan must be defined clearly otherwise it will fail while creating database connection. Another point is different entity managers must have different packages as well. It is not possible to use a com.test.repositories package and make both scan in there.
Datasource configuration is almost the same as the previous one but this time let’s use configuration annotation. DataSourceConfiguration file will be defined as:
Next step is defining an EntityManager. Be aware of the base package io.msdalp.dsone to be scanned. First entity manager will deal with datasource one and everything related to it will be stored in io.msdalp.dsone. Also do not forget to update Hibernate Dialect if you are using a different database.
Second entity manager will be exactly the same with this one but only different identifiers. It is using the second datasource and scanning io.msdalp.dstwo.
With these configurations any repository or entity defined under package io.msdalp.dsone will work with Blog database and io.msdalp.dstwo with Log database.