Configure Multiple Database’s in SpringBoot application

We can customize the configurations in the .yml file as shown in the below

 YML File

#### DB2 Properties
db2:
 
datasource:
   
jdbc-url: jdbc:db2://SERVER:PORT/DBNAME
   
driver-class-name: com.ibm.db2.jcc.DB2Driver
   
testWhileIdle: true
   
validationQuery: SELECT 1
   
username:
   
passwrod:

#### Oracle properties
oracle:
 
datasource:
   
jdbc-url: jdbc:oracle:thin:@SERVER:PORT:DBNAME
   
driver-class-name: oracle.jdbc.OracleDriver
   
username:
   
password:

 

Map the above YML properties to DataSource programmatically for each Database

DB2DatabaseConfig.java

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import javax.sql.DataSource;
@Configuration @ConfigurationProperties(prefix = "db2.datasource") public class DB2DatabaseConfig extends HikariConfig {
   
@Bean     @Qualifier("db2")     @Primary
   
public DataSource db2DataSource() {         return new HikariDataSource(this);     }

   
@Bean     @Qualifier("db2")     public NamedParameterJdbcTemplate db2JdbcTemplate() {         return new NamedParameterJdbcTemplate(db2DataSource());     } }

 

OracleDatabaseConfig.java

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration @ConfigurationProperties(prefix = "oracle.datasource") public class OracleDatabaseConfig extends HikariConfig {
   
@Bean     @Qualifier("oracle")     public DataSource oracleDataSource() {         return new HikariDataSource(this);     }
   
@Bean     @Qualifier("oracle")     public JdbcTemplate oracleJdbcTemplate() throws SQLException {         return new JdbcTemplate(oracleDataSource());     } }

 

As usual, we can use the above configurations in the repository class as below for Oracle DB

@Repository
public class LocationRepository {

   
@Autowired     @Qualifier("oracle")     JdbcTemplate oracleJdbcTemplate;
    public void getLocation(){
// write code here     }
}

We can connect DB2 as below

@Mapper
public interface TestMapper {
   
// Write your code here
}

 

No comments:

Post a Comment