Spring Boot JPA Multiple Datasources
Author:
Ramesh Fadatare
π Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this article, we will learn how to configure multiple data sources and connect to multiple databases in a typical Spring Boot web application.
We will create a Spring boot project to demonstrate how to configure multiple data sources and connect to multiple databases.
As we know that Spring Boot autoconfiguration works out of the box if you have a single database to work with and provides plenty of customization options through its properties. But if your application demands more control over the application configuration, you can turn off specific auto-configurations and configure the components by yourself.
In this article, we will learn step-by-step how to use multiple databases in the same application. If we need to connect to multiple databases, we need to configure various Spring beans like DataSources, TransactionManagers, EntityManagerFactoryBeans, DataSourceInitializers, etc., explicitly.
What we'll build?
We will build a Spring Boot web application where the security data has been stored in one database and order-related data has been stored in another database.
Let's see how we can work with multiple databases in Spring Boot and use the Spring Data JPA-based application.
Tools and Technologies Used
- Spring Boot - 3+
- JDK - 17 or later
- Spring Framework - 6+
- Hibernate - 6+
- Maven - 3.2+
- JPA
- H2
- Thymeleaf
- IDE - Eclipse or Spring Tool Suite (STS)
Create and Set up a Spring Boot Project
There are many ways to create a Spring Boot application. The simplest way is to use Spring Initializr at http://start.spring.io/, which is an online Spring Boot application generator.
Use the following details while creating the Spring boot project:
- Generate: Maven Project
- Java Version: 17 (Default)
- Spring Boot: 3.0.4
- Group: net.guides.springboot
- Artifact: springboot-multiple-datasources
- Name: springboot-multiple-datasources
- Description: Rest API for a Simple User Management Application
- Package Name : net.guides.springboot.springbootmultipledatasources
- Packaging: jar (This is the default value)
- Dependencies: Web, JPA, H2, DevTools
Maven pom.xml File
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.guides.springboot</groupId>
<artifactId>springboot-multiple-datasources</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-multiple-datasources</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.4</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>Packaging Structure
Following is the packing structure -
Excluding the AutoConfiguration classes
Let's turn off the DataSource JPA-related autoconfiguration classes. As we are going to configure the database-related beans explicitly, we will turn off the DataSource JPA Autoconfiguration by excluding the AutoConfiguration classes:package net.guides.springboot.springbootmultipledatasources; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication( exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class }) @EnableTransactionManagement public class SpringbootMultipleDatasourcesApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMultipleDatasourcesApplication.class, args); } }
Configure Multiple Datasource Properties
H2 Database Configuration
Let's configure the H2 datasource properties. Configure the Security and Orders database connection parameters in the application.properties file.debug=true
datasource.security.driver-class-name=org.h2.Driver
datasource.security.url=jdbc:h2:mem:securitydb;DB_CLOSE_DELAY=-1
datasource.security.username=sa
datasource.security.password=
datasource.security.initialize=true
datasource.orders.driver-class-name=org.h2.Driver
datasource.orders.url=jdbc:h2:mem:ordersdb;DB_CLOSE_DELAY=-1
datasource.orders.username=sa
datasource.orders.password=
datasource.orders.initialize=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
MySQL Database Configuration
We are using an H2 database to quickly set up the application but you can also use MySQL database for production by replacing the below configuration in an application.properties file.
datasource.security.driver-class-name=com.mysql.jdbc.Driver
datasource.security.url=jdbc:mysql://localhost:3306/securitydb
datasource.security.username=root
datasource.security.password=root
datasource.security.initialize=true
datasource.orders.driver-class-name=com.mysql.jdbc.Driver
datasource.orders.url=jdbc:mysql://localhost:3306/ordersdb
datasource.orders.username=root
datasource.orders.password=root
datasource.orders.initialize=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Note that we have used custom property keys to configure the two datasource properties. In the next step, we will create a security-related JPA entity and a JPA repository.
Create JPA Entites - User and Address
User
package net.guides.springboot.springbootmultipledatasources.security.entities; import java.util.Set; import jakarta.persistence.*; /** * @author Ramesh Fadatare * */ @Entity @Table(name="USERS") public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column(nullable=false) private String name; @Column(nullable=false, unique=true) private String email; private boolean disabled; @OneToMany(mappedBy="user") private Set<Address> addresses; public User() { } public User(Integer id, String name, String email) { this.id = id; this.name = name; this.email = email; } public User(Integer id, String name, String email, boolean disabled) { this.id = id; this.name = name; this.email = email; this.disabled = disabled; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public Set<Address> getAddresses() { return addresses; } public void setAddresses(Set<Address> addresses) { this.addresses = addresses; } }
Address
package net.guides.springboot.springbootmultipledatasources.security.entities; import jakarta.persistence.*; /** * @author Ramesh Fadatare * */ @Entity @Table(name="ADDRESSES") public class Address { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column(nullable=false) private String city; @ManyToOne @JoinColumn(name="user_id") private User user; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
Spring JPA Repository - UserRepository.java
package net.guides.springboot.springbootmultipledatasources.security.repositories; import org.springframework.data.jpa.repository.JpaRepository; import net.guides.springboot.springbootmultipledatasources.security.entities.User; /** * @author Ramesh Fadatare * */ public interface UserRepository extends JpaRepository<User, Integer> { }
Create JPA Entities - Order and OrderItem
Order
package net.guides.springboot.springbootmultipledatasources.orders.entities; import java.util.Set; import jakarta.persistence.*; /** * @author Ramesh Fadatare * */ @Entity @Table(name="ORDERS") public class Order { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column(nullable=false, name="cust_name") private String customerName; @Column(nullable=false, name="cust_email") private String customerEmail; @OneToMany(mappedBy="order") private Set<OrderItem> orderItems; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerEmail() { return customerEmail; } public void setCustomerEmail(String customerEmail) { this.customerEmail = customerEmail; } public Set<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(Set<OrderItem> orderItems) { this.orderItems = orderItems; } }
OrderItem
package net.guides.springboot.springbootmultipledatasources.orders.entities; import jakarta.persistence.*; /** * @author Ramesh Fadatare * */ @Entity @Table(name="ORDER_ITEMS") public class OrderItem { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String productCode; private int quantity; @ManyToOne @JoinColumn(name="order_id") private Order order; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
Spring JPA Repository - OrderRepository.java
package net.guides.springboot.springbootmultipledatasources.orders.repositories; import org.springframework.data.jpa.repository.JpaRepository; import net.guides.springboot.springbootmultipledatasources.orders.entities.Order; /** * @author Ramesh Fadatare * */ public interface OrderRepository extends JpaRepository<Order, Integer>{ }
Initialize Sample Data - security-data.sql script
Create SQL scripts to initialize sample data. Create the security-data.sql script in the src/main/resources folder to initialize the USERS table with sample data.
delete from addresses; delete from users; insert into users(id, name, email,disabled) values(1,'John Cena','john@gmail.com', false); insert into users(id, name, email,disabled) values(2,'Salman Khan','salman@gmail.com', false); insert into users(id, name, email,disabled) values(3,'Amitr Khan','amir@gmail.com', true); insert into addresses(id,city,user_id) values(1, 'Pune',1); insert into addresses(id,city,user_id) values(2, 'Landon',1); insert into addresses(id,city,user_id) values(3, 'Newyork',2); insert into addresses(id,city,user_id) values(4, 'Mumbai',3); insert into addresses(id,city,user_id) values(6, 'Washington',3);
Initialize Sample Data - orders-data.sql script
Create the orders-data.sql script in the src/main/resources folder to initialize the ORDERS table with sample data.
delete from order_items; delete from orders; insert into orders(id, cust_name, cust_email) values(1,'John Cena','john@gmail.com'); insert into orders(id, cust_name, cust_email) values(2,'Salman Khan','salman@gmail.com'); insert into orders(id, cust_name, cust_email) values(3,'Amir Khan','amir@gmail.com'); insert into order_items(id, productcode,quantity,order_id) values(1,'order item1', 2, 1); insert into order_items(id, productcode,quantity,order_id) values(2,'order item2', 1, 1); insert into order_items(id, productcode,quantity,order_id) values(3,'order item3', 5, 1); insert into order_items(id, productcode,quantity,order_id) values(4,'order item4', 2, 2); insert into order_items(id, productcode,quantity,order_id) values(5,'order item5', 1, 2);
Create Security Datasource Configuration - SecurityDataSourceConfig.java
Create the SecurityDataSourceConfig.java configuration class. we will configure the Spring beans such as DataSource, TransactionManager, EntityManagerFactoryBean, and DataSourceInitializer by connecting to the Security database in SecurityDataSourceConfig.javapackage net.guides.springboot.springbootmultipledatasources.config; import java.util.Properties; import jakarta.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; /** * @author Ramesh Fadatare * */ @Configuration @EnableJpaRepositories( basePackages = "net.guides.springboot.springbootmultipledatasources.security.repositories", entityManagerFactoryRef = "securityEntityManagerFactory", transactionManagerRef = "securityTransactionManager" ) public class SecurityDataSourceConfig { @Autowired private Environment env; @Bean @ConfigurationProperties(prefix="datasource.security") public DataSourceProperties securityDataSourceProperties() { return new DataSourceProperties(); } @Bean public DataSource securityDataSource() { DataSourceProperties securityDataSourceProperties = securityDataSourceProperties(); return DataSourceBuilder.create() .driverClassName(securityDataSourceProperties.getDriverClassName()) .url(securityDataSourceProperties.getUrl()) .username(securityDataSourceProperties.getUsername()) .password(securityDataSourceProperties.getPassword()) .build(); } @Bean public PlatformTransactionManager securityTransactionManager() { EntityManagerFactory factory = securityEntityManagerFactory().getObject(); return new JpaTransactionManager(factory); } @Bean public LocalContainerEntityManagerFactoryBean securityEntityManagerFactory() { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setDataSource(securityDataSource()); factory.setPackagesToScan(new String[]{"net.guides.springboot.springbootmultipledatasources.security.entities"}); factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto")); jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql")); factory.setJpaProperties(jpaProperties); return factory; } @Bean public DataSourceInitializer securityDataSourceInitializer() { DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); dataSourceInitializer.setDataSource(securityDataSource()); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("security-data.sql")); dataSourceInitializer.setDatabasePopulator(databasePopulator); dataSourceInitializer.setEnabled(env.getProperty("datasource.security.initialize", Boolean.class, false)); return dataSourceInitializer; } }
Note that you have populated the datasource.security.* properties into DataSourceProperties by using @ConfigurationProperties(prefix="datasource.security") and DataSourceBuilder fluent API to create the DataSource bean.
While creating the LocalContainerEntityManagerFactoryBean bean, you have configured the package called net.guides.springboot.springbootmultipledatasources.security.entities to scan for JPA entities. You have configured the DataSourceInitializer bean to initialize the sample data from security-data.sql.
Finally, we enabled Spring Data JPA support by using the @EnableJpaRepositories annotation. As we are going to have multiple EntityManagerFactory and TransactionManager beans, we configured the bean IDs for entityManagerFactoryRef and transactionManagerRef by pointing to the respective bean names. we also configured the basePackages property to indicate where to look for the Spring Data JPA repositories (the packages).
Create Security Datasource Configuration - OrdersDataSourceConfig.java
Create the OrdersDataSourceConfig.java configuration class. Similar to SecurityDataSourceConfig.java, you will create OrdersDataSourceConfig.java but point it to the Orders database.
package net.guides.springboot.springbootmultipledatasources.config; import java.util.Properties; import jakarta.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; /** * @author Ramesh Fadatare * */ @Configuration @EnableJpaRepositories( basePackages = "net.guides.springboot.springbootmultipledatasources.orders.repositories", entityManagerFactoryRef = "ordersEntityManagerFactory", transactionManagerRef = "ordersTransactionManager" ) public class OrdersDataSourceConfig { @Autowired private Environment env; @Bean @ConfigurationProperties(prefix = "datasource.orders") public DataSourceProperties ordersDataSourceProperties() { return new DataSourceProperties(); } @Bean public DataSource ordersDataSource() { DataSourceProperties primaryDataSourceProperties = ordersDataSourceProperties(); return DataSourceBuilder.create() .driverClassName(primaryDataSourceProperties.getDriverClassName()) .url(primaryDataSourceProperties.getUrl()) .username(primaryDataSourceProperties.getUsername()) .password(primaryDataSourceProperties.getPassword()) .build(); } @Bean public PlatformTransactionManager ordersTransactionManager() { EntityManagerFactory factory = ordersEntityManagerFactory().getObject(); return new JpaTransactionManager(factory); } @Bean public LocalContainerEntityManagerFactoryBean ordersEntityManagerFactory() { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setDataSource(ordersDataSource()); factory.setPackagesToScan(new String[] { "net.guides.springboot.springbootmultipledatasources.orders.entities" }); factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto")); jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql")); factory.setJpaProperties(jpaProperties); return factory; } @Bean public DataSourceInitializer ordersDataSourceInitializer() { DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); dataSourceInitializer.setDataSource(ordersDataSource()); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("orders-data.sql")); dataSourceInitializer.setDatabasePopulator(databasePopulator); dataSourceInitializer.setEnabled(env.getProperty("datasource.orders.initialize", Boolean.class, false)); return dataSourceInitializer; } }
Create UserOrdersService.java
package net.guides.springboot.springbootmultipledatasources.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import net.guides.springboot.springbootmultipledatasources.orders.entities.Order; import net.guides.springboot.springbootmultipledatasources.orders.repositories.OrderRepository; import net.guides.springboot.springbootmultipledatasources.security.entities.User; import net.guides.springboot.springbootmultipledatasources.security.repositories.UserRepository; /** * @author Ramesh Fadatare * */ @Service public class UserOrdersService { @Autowired private OrderRepository orderRepository; @Autowired private UserRepository userRepository; @Transactional(transactionManager="securityTransactionManager") public List<User> getUsers() { return userRepository.findAll(); } @Transactional(transactionManager="ordersTransactionManager") public List<Order> getOrders() { return orderRepository.findAll(); } }
Create HomeController.java
packagenet.guides.springboot.springbootmultipledatasources.controllers; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Controller; importorg.springframework.ui.Model; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importnet.guides.springboot.springbootmultipledatasources.services.UserOrdersService; /** * @author Ramesh Fadatare * */@ControllerpublicclassHomeController { @AutowiredprivateUserOrdersService userOrdersService; @RequestMapping(value= {"/", "/app/users"}, method=RequestMethod.GET) publicStringgetUsers(Modelmodel) { model.addAttribute("users", userOrdersService.getUsers()); model.addAttribute("orders", userOrdersService.getOrders()); return"users"; } }
Use OpenEntityManagerInViewFilter for Multiple Data Sources
Let's see how to use OpenEntityManagerInViewFilter to enable lazy loading of JPA entity LAZY associated collections while rendering the view, you need to register the OpenEntityManagerInViewFilter beans.
/** * */ package net.guides.springboot.springbootmultipledatasources.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * @author Ramesh Fadatare * */ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Bean public OpenEntityManagerInViewFilter securityOpenEntityManagerInViewFilter() { OpenEntityManagerInViewFilter osivFilter = new OpenEntityManagerInViewFilter(); osivFilter.setEntityManagerFactoryBeanName("securityEntityManagerFactory"); return osivFilter; } @Bean public OpenEntityManagerInViewFilter ordersOpenEntityManagerInViewFilter() { OpenEntityManagerInViewFilter osivFilter = new OpenEntityManagerInViewFilter(); osivFilter.setEntityManagerFactoryBeanName("ordersEntityManagerFactory"); return osivFilter; } }
As we are building a web application so the method returns the users.html view.
Create Thymeleaf page - users.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot</title>
</head>
<body>
<div style="width: 20%; float:left">
<h1>Users</h1>
<hr/>
<div th:each="user : ${users}">
<h2>Name: <span th:text="${user.name}">Name</span></h2>
<h4>Addresses</h4>
<div th:each="addr : ${user.addresses}">
<p th:text="${addr.city}">City</p>
</div>
</div>
</div>
<div style="width: 80%; float:right">
<h1>Orders</h1>
<hr/>
<div th:each="order : ${orders}">
<h2>Customer Name: <span th:text="${order.customerName}">customerName</span></h2>
<h4>Order Items</h4>
<div th:each="item : ${order.orderItems}">
<p th:text="${item.productCode}">productCode</p>
</div>
</div>
</div>
</body>
</html>Running an Application
The SpringbootMultipleDatasourcesApplication.java is an entry point so right-click and choose run as in your IDE will start the embedded tomcat server on port 8080.
Hit http://localhost:8080/ link in a browser will display below web page on a browser.
Output
That's all, I am done with developing a Spring Boot web application with multiple datasources.
Source Code on GitHub
Download the source code of this example at my GitHub repository at https://github.com/RameshMF/springboot-jpa-multiple-datasourcesRelated Spring Boot and Microservices Tutorials/Guides:
The Hidden Magic of Spring Boot: Secrets Every Developer Should Know What Happens When You Hit a Spring Boot REST API Endpoint (Behind the Scenes) Spring Boot Exception Handling Build CRUD REST API with Spring Boot, Spring Data JPA, Hibernate, and MySQL Spring Boot DELETE REST API: @DeleteMapping Annotation Spring Boot PUT REST API — @PutMapping Annotation Spring Boot POST REST API Spring Boot GET REST API — @GetMapping Annotation Spring Boot REST API with Request Param | Spring Boot Course Spring Boot REST API with Path Variable — @PathVariable Chapter 13: Understanding @SpringBootApplication Annotation | Spring Boot Course Chapter 5: Create Spring Boot Project and Build Hello World REST API | Spring Boot Course 10 Real-World Spring Boot Architecture Tips Every Developer Should Follow Top 10 Spring Boot Tricks Every Java Developer Should Know Debugging Spring Dependency Injection Issues - Very Important Common Code Smells in Spring Applications — How to Fix Them Spring Boot + OpenAI ChatGPT API Integration Tutorial Spring Boot Course -> New Series on Medium ❤️ Spring Boot Microservices with RabbitMQ Example React JS + Spring Boot Microservices Dockerizing a Spring Boot Application How to Change the Default Port in Spring Boot How to Change Context Path in Spring Boot Top 10 Spring Boot REST API Mistakes and How to Avoid Them (2025 Update) Spring Boot REST API Best Practices Spring Boot Security Database Authentication Example Tutorial Spring Boot Security Form-Based Authentication Spring Boot Security In-Memory Authentication What is Spring Boot Really All About? Why Spring Boot over Spring? Top 10 Spring Boot Key Features That You Should Know Spring vs Spring Boot Setting Up the Development Environment for Spring Boot Spring Boot Auto-Configuration: A Quick Guide Spring Boot Starters Quick Guide to Spring Boot Parent Starter Spring Boot Embedded Servers Spring Boot Thymeleaf Hello World Example Chapter 10: Spring Boot DevTools | Spring Boot Course Chapter 13: Spring Boot REST API That Returns JSON | Spring Boot Course Spring Boot REST API That Returns List of Java Objects in JSON Format Top 10 Spring Boot Mistakes and How to Avoid Them Advanced Spring Boot Concepts that Every Java Developer Should Know What Are Microservices in Spring Boot? Integrating React Frontend with Spring Boot ChatGPT API (Step-by-Step Guide) Build a Chatbot Using Spring Boot, React JS, and ChatGPT API Top 10 Mistakes in Spring Boot Microservices and How to Avoid Them (With Examples) Spring Boot Security Best Practices: Protecting Your Application from Attacks π Dependency Injection in Spring (Explained with Coding Examples) ⚙️ How Spring Container Works Behind the Scenes How Spring Container Works Behind the Scenes (Spring Container Secrets Revealed!) Spring @Component vs @Bean vs @Service vs @Repository Explained How Component Scanning Works Behind the Scenes in Spring How Spring Autowiring Works Internally Top 20 Spring Boot Best Practices for Java Developers Build Spring Boot React Full Stack Project — Todo App [2025 Update] Spring vs Spring MVC vs Spring Boot Spring Boot Best Practices: Use DTOs Instead of Entities in API Responses Spring Boot DTO Tutorial (Using Java record) – Complete CRUD REST API Implementation Spring Boot Architecture: Controller, Service, Repository, Database and Architecture Flow Java Stream filter() Method with Real-World Examples Spring Boot Auto Configuration Explained | How It Works Spring Boot Profiles: How to Manage Environment-Based Configurations Create a Custom Spring Boot Starter | Step-by-Step Guide Spring Boot Starter Modules Explained | Auto-Configuration Guide Deploy Spring Boot Applications with Profile-Based Settings | Step-by-Step Guide Spring Boot Performance Tuning: 10 Best Practices for High Performance Spring Boot @ComponentScan Annotation | Customizing Component Scanning Difference Between @RestController and @RequestMapping in Spring Boot Spring Boot @Cacheable Annotation – Improve Performance with Caching Spring Boot Redis Cache — @Cacheable Complete Guide When to Use @Service, @Repository, @Controller, and @Component Annotations in Spring Boot Why, When, and How to Use @Bean Annotation in Spring Boot App Java Spring Boot vs. Go (Golang) for Backend Development in 2025 Is Autowired Annotation Deprecated in Spring Boot? Everything You Need to Know π« Stop Making These Common Mistakes in Spring Boot Projects Top 10 Mind-Blowing Spring Boot Tricks for Beginners Why Choose Spring Boot Over Spring Framework? | Key Differences and Benefits How to Run a Spring Boot Application | 5 Easy Ways for Developers What is AutoConfiguration in Spring Boot? | Explained with Example Customize Default Configuration in Spring Boot | 5 Proven Ways Chapter 12: Understanding SpringApplication.run() Method Internals | Spring Boot Course What is CommandLineRunner in Spring Boot? How to Create Custom Bean Validation in Spring Boot Can You Build a Non-Web Application with Spring Boot? How to Disable Auto-Configuration in Spring Boot (Step-by-Step Guide) Top 25 Spring Boot Interview Questions and Answers for Beginners How to Use Java Records with Spring Boot Spring Boot Constructor Injection Explained with Step-by-Step Example π« Stop Using @Transactional Everywhere: Understand When You Actually Need It π« Stop Writing Fat Controllers: Follow the Controller-Service-Repository Pattern π« Stop Using Field Injection in Spring Boot: Use Constructor Injection π« Stop Sharing Databases Between Microservices: Use Database Per Service Pattern 10 Java Microservices Best Practices Every Developer Should Follow How to Choose the Right Java Microservices Communication Style (Sync vs Async) How to Implement Event-Driven Communication in Java Microservices (Step-by-Step Guide with Kafka) Stop Building Tight-Coupled Microservices: Aim for Loose Coupling Spring Boot Microservices E-Commerce Project: Step-by-Step Guide Spring Boot Microservices with RabbitMQ Example React JS + Spring Boot Microservices The Ultimate Microservices Roadmap for Beginners: Building Modern Scalable Systems What Are Microservices in Spring Boot? Top 5 Message Brokers Every Developer Should Know Top 10 Spring Cloud Microservices Best Practices [Removed Deprecated Features] Best Tools for Microservices Development in 2025 How to Break a Monolithic Application into Microservices (E-Commerce Use Case) Monoliths Aren’t Dead — Microservices Are Just Overused When to Break a Monolith: A Developer’s Checklist π Java Is Still the King of Microservices — And Here’s the Proof 5 Microservices Design Patterns You Must Know in 2025 Bulkhead Pattern in Microservices — Improve Resilience and Fault Isolation Strangler Fig Pattern in Microservices — Migrate Monolith to Microservices Event Sourcing Pattern in Microservices (With Real-World Example) Circuit Breaker Pattern in Microservices using Spring Boot 3, WebClient and Resilience4j CQRS Pattern in Microservices Aggregator Design Pattern in Microservices — A Complete Guide Database Per Service Pattern in Microservices API Gateway Pattern in Microservices — A Complete Guide Saga Pattern in Microservices: A Step-by-Step Guide Microservices Are a Mess Without These Java Design Patterns️ Java Microservices Interview Questions and Answers for Freshers Top Microservices Interview Questions and Answers for Experienced Professionals Top 10 Microservices Design Pattern Interview Questions and Answers Top Microservices Tricky Interview Questions You Should Know (With Answers) Microservices Best Practices: Building Scalable and Resilient Systems Why Microservices Are the Future of Software Architecture Microservices with Spring Cloud: Simplify Your Architecture Spring Boot and Microservices Roadmap for Beginners [2025 Update] Best Programming Language for Microservices Project Development in 2025 My 50+ Must-Read Microservices Tutorials, Articles and Guides on the Medium Platform
(θΏ½θ¨)
(θΏ½θ¨γγγΎγ§)
Comments
eh seguido la secuencia de su post de conexion multiple perono pude correr el codigo a causa de que uno de las clases que indica ya que puso el mismo codigo en
Reply DeleteSecurityDataSourceConfig --> aqui esta bien el codigo
OrdersDataSourceConfig --> aqui repitio el mismo codigo de SecurityDataSourceConfig
podria pasarme el proyecto apra ejecutarlo o en defecto la clase que me falta para ejecutar el codigo gracias mi correo es elitgamaliel@gmail.com
You can download source code of this example at my GitHub repository https://github.com/RameshMF/springboot-jpa-multiple-datasources
Deletetypos in OrdersDataSourceConfig.java source code
Reply DeleteCorrected. Thanks for pointing that.
DeleteNoticed none of the configuration was specify as @Primary. It lead to multiple entityManagerFactory exception message. Also, the DataSourceInitializer is optional.
Reply DeleteCan we Map User and Order table, i have a scenario in that i have to map one DB table ie.(User) with another DB table ie. (Order)
Reply DeleteCan we Map User and Order table, i have a scenario in that i have to map one DB table ie.(User) with another DB table ie. (Order)
Reply Deletehi ,
Reply Deleteis that same code will work in linux environment,or do i need to do any minor change
Post a Comment
Leave Comment
[γγ¬γΌγ ]