Monday, May 13, 2019

Spring Boot Multiple Database Configuration Example

Q- How to configure two database in spring boot application?

Spring Boot Multiple Database Configuration Example

Step -1: Add the dependencies in  pom.xml 

  • spring-boot-starter-data-jpa: It provides key dependencies for Hibernate, Spring Data JPA and Spring ORM.

Step -2: Add datasource properties into  application.properties  file. for each database like dbName1 and dbName2
  • spring.dbName1.datasource.url=jdbc:mysql://localhost:3306/databaseName
  • spring.dbName1.datasource.username=username
  • spring.dbName1.datasource.password=password
  • spring.dbName1.datasource.driver-class-name=oracle.jdbc.OracleDriver   // You often do not need to specify the driver-class-name, since Spring Boot can deduce it for most databases from the url.
  • spring.jpa.database=default    // Set the SQL Dialect to “default” in application.properties to let Spring autodetect the different SQL Dialects for datasource  

Step -3: Create configuration file for each database.In each one of this configuration classes, should be define the following interfaces:

  • DataSource
  • EntityManagerFactory
  • TransactionManager

Suppose you are using Mysql database for product & Oracle database for users
To configure- database1

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
  entityManagerFactoryRef = "mysqlEntityManagerFactory",
  transactionManagerRef = "mysqlTransactionManager",
  basePackages = { "com.shubh.product.repo" }
)
public class MysqlDbConfig {


}

To configure- database2

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
  entityManagerFactoryRef = "OracleEntityManagerFactory",
  transactionManagerRef = "OracleTransactionManager",
  basePackages = { "com.shubh.user.repo" }
)
public class OracleDbConfig {


}

See the complete example Spring Boot With Multiple Datasources Configuration

No comments:

Post a Comment