헤르메스 LIFE

[Spring Boot] DataSource를 이용한 Multi Database Connection 샘플 본문

Spring Framework

[Spring Boot] DataSource를 이용한 Multi Database Connection 샘플

헤르메스의날개 2021. 1. 11. 20:16
728x90

출처 ; parandol.tistory.com/17

MultiDatabaseSample.zip
0.05MB

개발환경

Framework ; Spring Boot 2.2.4 + MyBatis

JDK : JDK 1.8.0_202

Database : MSSQL : 개발을 위해 MSSQL 하나로 두개의 Connection 을 생성했습니다.


pom.xml

<?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>com.rest</groupId>
    <artifactId>MultiDatabaseSample</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <java.version>1.8</java.version>
    </properties>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!--
                 스프링 부트에서 Log4j2를 사용하기위해선 내부로깅에서 쓰이는 의존성을 제외해주어야 합니다.
                 기본적으로 Spring은 Slf4j라는 로깅 프레임워크를 사용합니다.
                 구현체를 손쉽게 교체할 수 있도록 도와주는 프레임 워크입니다.
                 Slf4j는 인터페이스고 내부 구현체로 logback을 가지고 있는데,
                 Log4j2를 사용하기 위해 exclude 해야 합니다.
                 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- Log4j2 로깅 구현체를 사용을 위해 Spring Boot Starter에서 지원해주는  log4j2 의존성을 추가 해준다. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>
        <!-- MyBatis sql pretty -->
        <dependency>
            <groupId>org.bgee.log4jdbc-log4j2</groupId>
            <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
            <version>1.16</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <!-- MSSQL Server -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- yaml-resource-bundle -->
        <dependency>
            <groupId>net.rakugakibox.util</groupId>
            <artifactId>yaml-resource-bundle</artifactId>
            <version>1.1</version>
        </dependency>
    </dependencies>

    <!--  빌드 플러그인 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

log4jdbc.log4j2.properties

log4jdbc.spylogdelegator.name = net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
log4jdbc.dump.sql.maxlinelength = 0

application.yml - datasource 앞에 구분자를 줄 수 있습니다.

Spring Boot 는 hikari datasource 로 생성되는 것으로 보여집니다.

spring:
  profiles:
    active: local                       # 디폴트 환경
  # DB 설정
  mssql:
    datasource:
      driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
      jdbc-url: jdbc:log4jdbc:sqlserver://localhost:1433;databaseName=springboot
      username: spring
      password: spring
      auto-commit: false
      connection-test-query: SELECT 1
      minimum-idle: 3
      maximum-pool-size: 10
      pool-name: pool-mssql
      # mapper.xml 위치 지정
      # **은 하위 폴더 레벨에 상관없이 모든 경로를 뜻하며, *는 아무 이름이나 와도 된다는것을 뜻합니다.
      mapper-locations: classpath:/mybatis/mapper/mssql/**/*.xml
      # mapper.xml에서 resultType을 지정할 때 com.god.bo.test.vo.TestVo 대신 TestVo로 간략히 할 수 있다.
      #type-aliases-package: com.god.bo.test.vo
      mybatis-config: classpath:/mybatis/mybatis-config.xml
  # DB 설정
  second:
    datasource:
      driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
      jdbc-url: jdbc:log4jdbc:sqlserver://localhost:14333;databaseName=springboot
      username: spring
      password: spring
      auto-commit: false
      connection-test-query: SELECT 1
      minimum-idle: 3
      maximum-pool-size: 10
      pool-name: pool-mssql
      # mapper.xml 위치 지정
      # **은 하위 폴더 레벨에 상관없이 모든 경로를 뜻하며, *는 아무 이름이나 와도 된다는것을 뜻합니다.
      mapper-locations: classpath:/mybatis/mapper/mssql/**/*.xml
      # mapper.xml에서 resultType을 지정할 때 com.god.bo.test.vo.TestVo 대신 TestVo로 간략히 할 수 있다.
      #type-aliases-package: com.god.bo.test.vo
      mybatis-config: classpath:/mybatis/mybatis-config.xml

application-local.yml

server:
  port: 8090                                # 서버 포트 변경

logging:
  level:
    root: warn
    multi.database: debug

spring:
  profiles: local

SpringRestApiApplication.java

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@Slf4j
public class SpringRestApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringRestApiApplication.class, args);
    }

}

MssqlConfig.java

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:/application.yml")
@MapperScan(value = "multi.database.mssql.dao", sqlSessionFactoryRef = "mssqlSqlSessionFactory")
public class MssqlConfig {
    private static final Logger logger = LoggerFactory.getLogger(MssqlConfig.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${spring.mssql.datasource.mapper-locations}")
    private String mapperLocations;

    @Value("${spring.mssql.datasource.mybatis-config}")
    private String configPath;

    @Value("${spring.mssql.datasource.driver-class-name}")
    private String dbDriverClassName;
    @Value("${spring.mssql.datasource.jdbc-url}")
    private String dbJdbcUrl;

    @Value("${spring.mssql.datasource.username}")
    private String dbUsername;

    @Value("${spring.mssql.datasource.password}")
    private String dbPassword;

    @Bean(name = "mssqlDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.mssql.datasource")
    public DataSource mssqlDataSource() {
        logger.debug("[MssqlConfig >> mssqlDataSource] dbDriverClassName :: {}", dbDriverClassName);
        logger.debug("[MssqlConfig >> mssqlDataSource] dbJdbcUrl :: {}", dbJdbcUrl);
        logger.debug("[MssqlConfig >> mssqlDataSource] dbUsername :: {}", dbUsername);
        logger.debug("[MssqlConfig >> mssqlDataSource] dbPassword :: {}", dbPassword);

        DataSource dataSource = DataSourceBuilder.create().build();

//        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
//        dataSourceBuilder.driverClassName(dbDriverClassName);
//        dataSourceBuilder.url(dbJdbcUrl);
//        dataSourceBuilder.username(dbUsername);
//        dataSourceBuilder.password(dbPassword);
//        DataSource dataSource = dataSourceBuilder.build();

        logger.info("Datasource : {}", dataSource);

        return dataSource;
    }

    @Bean(name = "mssqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory mssqlSqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources(mapperLocations));

        logger.debug("[MssqlConfig >> mssqlSqlSessionFactory] mapperLocations :: {}", mapperLocations);
        logger.debug("[MssqlConfig >> mssqlSqlSessionFactory] getResources :: {}",
                                                     applicationContext.getResources(mapperLocations));

//		Properties properties = new Properties();
//		properties.put("mapUnderscoreToCamelCase", true);
//		sqlSessionFactoryBean.setConfigurationProperties(properties);

        //Mybatis config파일 위치
        Resource myBatisConfig = new PathMatchingResourcePatternResolver().getResource(configPath);
        sqlSessionFactoryBean.setConfigLocation(myBatisConfig);

        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "mssqlSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate mssqlSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

SecondConfig.java - 이건 MssqlConfig.java 의 복제 입니다.

다만 다른 내용이 있다면.. Primary 를 삭제 됐습니다.

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:/application.yml")
@MapperScan(value = "multi.database.mssql.dao", sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondConfig {
    private static final Logger logger = LoggerFactory.getLogger(SecondConfig.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${spring.second.datasource.mapper-locations}")
    private String mapperLocations;

    @Value("${spring.second.datasource.mybatis-config}")
    private String configPath;

    @Value("${spring.second.datasource.driver-class-name}")
    private String dbDriverClassName;
    @Value("${spring.second.datasource.jdbc-url}")
    private String dbJdbcUrl;

    @Value("${spring.second.datasource.username}")
    private String dbUsername;

    @Value("${spring.second.datasource.password}")
    private String dbPassword;

    @Bean(name = "secondDataSource")
    //@Primary              Second 는 Primary 가 아님.
    @ConfigurationProperties(prefix = "spring.second.datasource")
    public DataSource secondDataSource() {
        logger.debug("[SecondConfig >> secondDataSource] dbDriverClassName :: {}", dbDriverClassName);
        logger.debug("[SecondConfig >> secondDataSource] dbJdbcUrl :: {}", dbJdbcUrl);
        logger.debug("[SecondConfig >> secondDataSource] dbUsername :: {}", dbUsername);
        logger.debug("[SecondConfig >> secondDataSource] dbPassword :: {}", dbPassword);

        DataSource dataSource = DataSourceBuilder.create().build();

//        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
//        dataSourceBuilder.driverClassName(dbDriverClassName);
//        dataSourceBuilder.url(dbJdbcUrl);
//        dataSourceBuilder.username(dbUsername);
//        dataSourceBuilder.password(dbPassword);
//        DataSource dataSource = dataSourceBuilder.build();

        logger.info("Datasource : {}", dataSource);

        return dataSource;
    }

    @Bean(name = "secondSqlSessionFactory")
    //@Primary              Second 는 Primary 가 아님.
    public SqlSessionFactory secondSqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        logger.debug("[SecondConfig >> secondSqlSessionFactory] mapperLocations :: {}", mapperLocations);
        logger.debug("[SecondConfig >> secondSqlSessionFactory] getResources :: {}", applicationContext.getResources(mapperLocations));

        sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources(mapperLocations));

//		Properties properties = new Properties();
//		properties.put("mapUnderscoreToCamelCase", true);
//		sqlSessionFactoryBean.setConfigurationProperties(properties);

        //Mybatis config파일 위치
        Resource myBatisConfig = new PathMatchingResourcePatternResolver().getResource(configPath);
        sqlSessionFactoryBean.setConfigLocation(myBatisConfig);

        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "secondSqlSessionTemplate")
    //@Primary              Second 는 Primary 가 아님.
    public SqlSessionTemplate secondSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<!-- <setting name="cacheEnabled" value="true"/> default value -->
		<!-- <setting name="cacheEnabled" value="false"/> -->
		<setting name="lazyLoadingEnabled" value="false"/>
		<!-- <setting name="multipleResultSetsEnabled" value="true"/> default value -->
		<!-- <setting name="useColumnLabel" value="true"/> default value -->
		<!-- <setting name="useGeneratedKeys" value="false"/> default value -->
		<!-- <setting name="defaultExecutorType" value="SIMPLE"/> default value -->
		<setting name="defaultStatementTimeout" value="25000"/>
		<setting name="mapUnderscoreToCamelCase" value="true"/>
		<setting name="localCacheScope" value="STATEMENT"/>
		<setting name="jdbcTypeForNull" value="CHAR"/>
	</settings>

</configuration>

TestSqlMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tbUser">
    
    <select id="select1" resultType="Map">
/* UserSqlMapper - select */
SELECT *
  FROM TB_USER
    </select>
</mapper>

 

이제 테스트를 위해 두 개의 Dao를 생성합니다.

MssqlRestDao.java

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class MssqlRestDao {

    @Autowired
    @Qualifier("mssqlSqlSessionTemplate")
    private SqlSessionTemplate sqlSession;

    /* test 조회 */
    public List<Map> selectList(Object param) {
        return sqlSession.selectList("com.tbUser.select1");
    }
}

SecondRestDao.java

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class SecondRestDao {

    @Autowired
    @Qualifier("secondSqlSessionTemplate")
    private SqlSessionTemplate sqlSession;

    /* test 조회 */
    public List<Map> selectList(Object param) {
        return sqlSession.selectList("com.tbUser.select2");
    }
}

DaoTest,java ( TDD 가 유행이라.. )

import lombok.extern.slf4j.Slf4j;
import multi.database.config.MssqlConfig;
import multi.database.config.SecondConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
@Slf4j
public class DaoTest {
    @Autowired
    MssqlRestDao mssqlRestDao;

    @Autowired
    SecondRestDao secondRestDao;

    @Test
    public void selectMssqltList() {
        log.debug("{}", mssqlRestDao.selectList("1"));
    }

    @Test
    public void selectSecondList() {
        log.debug("{}", mssqlRestDao.selectList("1"));
    }

}

 

결과 - 결과는 같지만 연결은 다르게 되었다는 것을 확인 할 수 있습니다.

2021-01-11 21:47:37.032 INFO 15128 --- [ main] m.d.m.d.DaoTest : Starting DaoTest on DESKTOP-HMJ6ST0 with PID 15128 (started by hermeswing in C:\JetBrains\IdeaProjects\MultiDatabaseSample) 2021-01-11 21:47:37.043 DEBUG 15128 --- [ main] m.d.m.d.DaoTest : Running with Spring Boot v2.2.4.RELEASE, Spring v5.2.3.RELEASE 2021-01-11 21:47:37.044 INFO 15128 --- [ main] m.d.m.d.DaoTest : The following profiles are active: local 2021-01-11 21:47:38.005 WARN 15128 --- [ main] o.m.s.m.ClassPathMapperScanner : No MyBatis mapper was found in '[multi.database.mssql.dao]' package. Please check your configuration. 2021-01-11 21:47:38.008 WARN 15128 --- [ main] o.m.s.m.ClassPathMapperScanner : No MyBatis mapper was found in '[multi.database.mssql.dao]' package. Please check your configuration. 2021-01-11 21:47:38.438 DEBUG 15128 --- [ main] m.d.c.MssqlConfig : [MssqlConfig >> mssqlDataSource] dbDriverClassName :: net.sf.log4jdbc.sql.jdbcapi.DriverSpy 2021-01-11 21:47:38.438 DEBUG 15128 --- [ main] m.d.c.MssqlConfig : [MssqlConfig >> mssqlDataSource] dbJdbcUrl :: jdbc:log4jdbc:sqlserver://localhost:1433;databaseName=springboot 2021-01-11 21:47:38.438 DEBUG 15128 --- [ main] m.d.c.MssqlConfig : [MssqlConfig >> mssqlDataSource] dbUsername :: spring 2021-01-11 21:47:38.438 DEBUG 15128 --- [ main] m.d.c.MssqlConfig : [MssqlConfig >> mssqlDataSource] dbPassword :: springboot 2021-01-11 21:47:38.455 INFO 15128 --- [ main] m.d.c.MssqlConfig : Datasource : HikariDataSource (null) 2021-01-11 21:47:38.628 DEBUG 15128 --- [ main] m.d.c.MssqlConfig : [MssqlConfig >> mssqlSqlSessionFactory] mapperLocations :: classpath:/mybatis/mapper/mssql/**/*.xml 2021-01-11 21:47:38.629 DEBUG 15128 --- [ main] m.d.c.MssqlConfig : [MssqlConfig >> mssqlSqlSessionFactory] getResources :: file [C:\JetBrains\IdeaProjects\MultiDatabaseSample\target\classes\mybatis\mapper\mssql\TestSqlMapper.xml] 2021-01-11 21:47:38.855 DEBUG 15128 --- [ main] m.d.c.SecondConfig : [SecondConfig >> secondDataSource] dbDriverClassName :: net.sf.log4jdbc.sql.jdbcapi.DriverSpy 2021-01-11 21:47:38.855 DEBUG 15128 --- [ main] m.d.c.SecondConfig : [SecondConfig >> secondDataSource] dbJdbcUrl :: jdbc:log4jdbc:sqlserver://localhost:1433;databaseName=springboot 2021-01-11 21:47:38.855 DEBUG 15128 --- [ main] m.d.c.SecondConfig : [SecondConfig >> secondDataSource] dbUsername :: springboot 2021-01-11 21:47:38.855 DEBUG 15128 --- [ main] m.d.c.SecondConfig : [SecondConfig >> secondDataSource] dbPassword :: springboot 2021-01-11 21:47:38.858 INFO 15128 --- [ main] m.d.c.SecondConfig : Datasource : HikariDataSource (null) 2021-01-11 21:47:38.864 DEBUG 15128 --- [ main] m.d.c.SecondConfig : [SecondConfig >> secondSqlSessionFactory] mapperLocations :: classpath:/mybatis/mapper/mssql/**/*.xml 2021-01-11 21:47:38.865 DEBUG 15128 --- [ main] m.d.c.SecondConfig : [SecondConfig >> secondSqlSessionFactory] getResources :: file [C:\JetBrains\IdeaProjects\MultiDatabaseSample\target\classes\mybatis\mapper\mssql\TestSqlMapper.xml] 2021-01-11 21:47:40.973 INFO 15128 --- [ main] m.d.m.d.DaoTest : Started DaoTest in 4.421 seconds (JVM running for 7.098) 2021-01-11 21:47:42.200 DEBUG 15128 --- [ main] m.d.m.d.DaoTest : [{PASSWORD=aa, USERNAME=aa, ROLE_ID=1, ID=4}, {PASSWORD=bb, USERNAME=cc, ROLE_ID=444, ID=5}, {PASSWORD=cc, USERNAME=cc, ROLE_ID=3, ID=6}] 2021-01-11 21:47:42.230 DEBUG 15128 --- [ main] m.d.m.d.DaoTest : [{PASSWORD=aa, USERNAME=aa, ROLE_ID=1, ID=4}, {PASSWORD=bb, USERNAME=cc, ROLE_ID=444, ID=5}, {PASSWORD=cc, USERNAME=cc, ROLE_ID=3, ID=6}] Process finished with exit code 0

참조 

https://gigas-blog.tistory.com/122

 

[Spring] Spring Boot 2 Multiple DataSource

프로젝트를 진행하는데 기존 시스템이 있는곳이라 DB를 2개 이상 사용해야된다고 합니다. 이제 Spring Boot 2.x 를 공부겸 진행하고 있는데 매번 난관이군요. 늘 생각하는거지만 실제론 쉬운 코드인

gigas-blog.tistory.com

 

728x90