When developing any application, it’s quite common to have to access multiple databases. Out of the box, Spring Boot provides easy access to a single datasource, in the simplest case just by specifying the JDBC driver on the class path!
Accessing multiple databases however, is still straightforward with Spring Boot. This article shows how to connect to two different MySql datasources from a Spring Boot application.
To showcase how to connect to to different databases, consider a products database and a customer database, with the following simplistic schema and data.
Database One - Products Database
create table PRODUCT(id integer, name varchar(255));
insert into PRODUCT(id, name) values (1, ‘XBox');
Database Two - Customer Database
create table CUSTOMER(id
insert into CUSTOMER(id, name) values (1, 'Daphne Jefferson’);
To access the databases, we need to declare a
JdbcTemplate for each database. In Spring, JdbcTemplates are created from a
DataSource which has a set of connection properties (url, username, password etc.)
In the above code we can see that a
@Configuration bean has been declared that defines a
customerDatasource and a
customerJdbcTemplate. Each of these beans are annotated with the
@Qualifier('customer...') to identify them as relating to the customer database.
Similarly, the above code defines a
productDataSource and a
productJdbcTemplate. Again these are annotated with
@Qualifier('product...') to identify them as relating to the product database.
DataSource Bean is annotated with the
@ConfigurationProperties(prefix="...datasource") annotation. This tells Spring Boot what properties within the
application.properties file should be used for connecting to each database. The
application.properties file therefore looks like the following:
Now that we’ve seen how to create a
JdbcTemplate, the JdbcTemplate can be injected into a
@Repository for use, e.g.
Again, note the use of the
@Qualifier annotation to specify which
JdbcTemplate is required for the different repositories.
ProductRepository is similarly written to access the
With a few simple steps, Spring Boot allows us to easily connect to multiple databases when using JdbcTemplates.