Spring Boot Data JPA by default supports connection with one db via Autoconfiguration, where we just need to give datasource inputs(e.g - driver class, url, username, password, dialect, etc.) in properties files and spring-boot takes care of rest.
But to create multiple DB in one service, we need to configure it by ourselves using java configuration style. Lets do this for two RDBMS, PostgreSQL and MySQL. Here for configuration of DBs, we need objects(beans) of implementation classes of:-
- DataSource (Interface),
- EntityManagerFactory (Interface), and
- TransactionManager (Interface).
PostgreSQL Database Commands:
cmd>psql -U postgres
create database db1
\c db1
\dt
select * from product;
MySQL Database Commands:
create database db2;
use db2;
show tables;
select * from customer;
- First create spring-boot-starter with data-Jpa, web, lombok, postgreSQL, MySQL, configuration-processor (for ConfigurationProperties), and devtools(to improve our development time).
- write application.properties
- Write your two model/entity classes, one each for PostgreSQL & MySQL. We wrote product and customer.
- Have to write two Repositories as well :- CustomerRepository and ProductRepository.
- The most important : write two config class, one each for Postgres & MySQL Databases.
- Runner for inserting data(or write your save methods).
- RestController to fetch data.
http://localhost:8080/products
http://localhost:8080/customer
References : https://www.baeldung.com/spring-data-jpa-multiple-databases