Connect to Different Types of Databases in Spring Boot

Nil Seri
1 min readNov 16, 2021

How to Connect to Multiple and Different Database Sources in Your Spring Boot Project

Photo by ben o'bro on Unsplash

I had described how to connect to different Cassandra database keyspaces in my previous post:

My project was implemented with Spring Boot 2.3.5 RELEASE.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
</parent>

These were my other dependencies used for database operations implementation:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

In addition to those, I had to connect to a MySQL database:

Please pay attention to “basePackages” and “mysqlDbEntityManager” for my MySQL model and repository folder. “persistenceUnit” name should be unique for each configuration in your project.

ConfigurationProperties “prefix” value is the prefix for database connection properties in application.properties file.

#==== MySQL Configuration ======#
spring.mysqldb.datasource.url=jdbc:mysql://127.0.0.1:3306/archive?useSSL=false
spring.mysqldb.datasource.username=admin
spring.mysqldb.datasource.password=password
spring.mysqldb.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

I declared this datasource as primary (by adding a “Primary” annotation).

Again, I implemented my model, repository and service classes just like I would in a single keyspace one.

Now we are good to go!

Happy Coding!

--

--

Nil Seri

I would love to change the world, but they won’t give me the source code | coding 👩🏻‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨