다중 데이터베이스 설정

프로젝트에 따라 Datasource를 여러개 설정해야하는 경우가 있다. 이때 여러개의 DB를 설정하는 방법에 대해 알아볼 것이다.

application.yml

설정할 Database정보를 application.yml 에 추가해준다.

databases:
  mysql:
  	first:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/spring_batch?serverTimezone=UTC
      username: test
      password: test
      driver-class-name: com.mysql.cj.jdbc.Driver
 		second:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
      username: test
      password: test
      driver-class-name: com.mysql.cj.jdbc.Driver
  h2:
    jdbc-url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    username: sa
    password:
    driver-class-name: org.h2.Driver

config 설정

MysqlMybatisConfig

MysqlSecondMybatisConfig

다음과 같이 설정해주면 된다.

  • @Primary 처음 스프링 구동 시 기본으로 사용할 Bean을 설정하는 것이다.

다음과 같이 별도 Bean 설정없이 @Autowired로 연결한 경우, @Primary로 설정한 mybatisSqlSessionFactory가 연결되며,

@Qualifier("mybatisSecondSqlSessionFactory")로 기본값이 빈을 연결할 수 있다.

참고

Last updated

Was this helpful?