[SPRING] 스프링과 마이바티스 에서 다중 데이타소스 사용하기

2017. 10. 19. 17:03·FrameWork/Spring
728x90
반응형

Spring 과 MyBatis (iBatis) 를 개발 환경으로 사용할 경우 여러 개의 datasource 를 써야 되는 경우가 있다.
여러 개의 data source 에 연결해야 할 경우 Mybatis config와 mapper 를 별도의 패키지로 분리하는게 개인적으로는 관리가 용이하다.

 

단위 테스트 및 stand-alone 용이라 Data Source 설정이 WAS에 있지 않고 
spring context 에 있고 BoneCP 나 c3p0 같은 Connection Pool 을 사용하지 않고 
스프링의 SimpleDriverDataSource 로 설정되어 있다.

 

database-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx.xsd
                http://www.springframework.org/schema/jee
                http://www.springframework.org/schema/jee/spring-jee.xsd">

    <!-- multiple data source & sqlSessionFactory -->
    <bean id="ds-one" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@//db1.example.com:1521/ocrl" />
        <property name="username" value="user" />
        <property name="password" value="userpwd" />
    </bean>
    <bean id="ds-two" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />       
        <property name="url" value="jdbc:mysql://db2.example.com:3306/lesstif?useUnicode=true&amp;characterEncoding=utf8" />
        <property name="username" value="userid" />
        <property name="password" value="useriduserPwd" />
    </bean>

    <bean id="dsOneSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:mapperLocations="classpath:/com/example/mapper-one/*mapper.xml"
        p:configLocation="classpath:/com/example/dsone-mybatis-config.xml"
        p:dataSource-ref="ds-one" />

    <bean id="dsTwoSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:mapperLocations="classpath:/com/example/mapper-two/*mapper.xml"
        p:configLocation="classpath:/com/example/dstwo-mybatis-config.xml"
        p:dataSource-ref="ds-two" />
     
    <bean id="dsOneScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="com.example.mapper-one" />
  
    <bean id="dsTwoScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="com.example.mapper-two" />

    <bean id="dsOnetransactionManager"   class="org.springframework.jdbc.datasource.DataSourceTransactionManager"    p:dataSource-ref="ds-one" />
    <bean id="dsTwotransactionManager"   class="org.springframework.jdbc.datasource.DataSourceTransactionManager"    p:dataSource-ref="ds-two" />

    <context:component-scan base-package="com.example.service-one, com.example.service-two">
    </context:component-scan>
</beans>

이 상태로 어플리케이션을 구동하면 다음과 비슷한 에러가 발생하고 디플로이가 안 될 것이다.

 

Ignoring bean creation exception on FactoryBean type check: org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'myMapper' defined in file : Unsatisfied dependency expressed through bean property 'sqlSessionFactory': : 
No qualifying bean of type [org.apache.ibatis.session.SqlSessionFactory] is defined: expected single matching bean but found 2: dsOneSqlSessionFactory, dsTwoSqlSessionFactory;

 

에러 메시지를 보면 두 개의 SqlSessionFactory 가 지정되어 있다고 표시되어 있다.

원인은 설정의 38 라인부터 42 라인까지 있는 MyBatis 의 MapperScannerConfigurer 가 어떤  SqlSessionFactory 를 참조해야 할지 몰라서 발생한다.



일단 내가 아는 해결 방법은 두 가지가 있다.

@Autowired 대신 @Resource 사용
@Resource(name="dsOneSqlSessionFactory")  처럼 어떤 sessionFactory 를 쓸지 Java Config 를 시용하여 Mapper 소스마다 지정해 준다.  
MyBatis 의 sqlSessionFactoryBeanName 을 사용해서 다음과 같이 매퍼에 어떤 sqlSessionFactoryBeanName 를 쓸지를 명시적으로 지정한다.

 

database-context.xml

<bean id="dsOneScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"
    p:basePackage="com.example.mapper-one"
    p:sqlSessionFactoryBeanName="dsOneSqlSessionFactory" />

<bean id="dsTwoScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"
    p:basePackage="com.example.mapper-two"
    p:sqlSessionFactoryBeanName="dsTwoSqlSessionFactory" />

728x90
반응형

'FrameWork > Spring' 카테고리의 다른 글

[SPRING] HTML5 SOCKET 통신 [sample]  (0) 2017.12.11
[SPRING] AOP를 이용하여 어노테이션(annotation) 만들기(활용 / 사용법)  (0) 2017.12.04
[Spring, JAVA] 파일 복사(FileChannel 이용)  (0) 2017.09.21
[SPRING] FTP서버의 이미지 프리뷰  (0) 2017.08.28
[Spring] [Excel] 웹에서 DB를 엑셀파일로 추출시키기.  (0) 2017.08.24
'FrameWork/Spring' 카테고리의 다른 글
  • [SPRING] HTML5 SOCKET 통신 [sample]
  • [SPRING] AOP를 이용하여 어노테이션(annotation) 만들기(활용 / 사용법)
  • [Spring, JAVA] 파일 복사(FileChannel 이용)
  • [SPRING] FTP서버의 이미지 프리뷰
밍글링글링
밍글링글링
mingling - 밍글링, 밍글밍글링. 코드와 어우러지다. IT/ 프로그래밍/소스
    반응형
    250x250
  • 밍글링글링
    mingling
    밍글링글링
  • 전체
    오늘
    어제
    • 밍글링글링 (407) N
      • Flutter (2)
      • 일상생활 (8)
        • 리뷰 (1)
        • 생활정보 (4)
        • 맛집 (0)
        • 여행 (0)
        • 모든정보 (3)
      • JAVA (126)
        • 개념 (6)
        • 예제 (115)
        • Exception (2)
      • C (1)
        • C (1)
        • C++ (0)
        • C# (0)
      • JS (29)
        • JavaScript (18)
        • JQuery (5)
        • AJax (0)
        • NODE.JS (6)
        • Angular.JS 2.0 (0)
      • WEB (87)
        • HTML (6)
        • CSS (61)
        • JSP (20)
        • JSTL (0)
      • FrameWork (8)
        • Spring (8)
        • BootStrap (0)
        • MyBATIS (0)
        • JUnit (0)
      • 외부 라이브러리 (5)
      • 공유 소스 관리 (5)
        • Git (5)
        • SVN (0)
      • 빅데이터 프로그래밍 (37)
        • Python (37)
        • R Programming (0)
      • DB (7)
        • ORACLE (0)
        • MySql (6)
      • Development Tools (7)
        • StarUML (0)
        • eXERD (0)
        • Eclipse (4)
      • SKILL (6)
        • Migration (0)
        • Security (6)
      • MicroSoft (0)
        • Excel (0)
        • Word (0)
      • Android (0)
      • Server (21)
        • Ubuntu (5)
        • Linux (15)
      • IOS (0)
      • XML (0)
      • 미디어 (0)
      • 공지사항 (3)
      • NETWORK (1)
      • 게임 (4)
        • 피파 (1)
        • 리니지M (0)
        • 배틀그라운드 (1)
        • 듀랑고 (2)
      • 세상 이슈 (6)
      • 일렉트론 (0)
      • 대회 소식 (4)
      • 업무 (2)
      • Express, Vue (6)
      • docker (11)
      • svelte (3)
      • 블록체인 (1)
      • IT (10) N
      • Rust (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    nginx
    css block
    java casting
    mysql db
    gitlab 설치
    자바 생성자
    리눅스 설치
    프런트엔드
    css table
    ssl 인증서 발급
    자바 배열
    오류
    자바 exception
    Rust lang
    proxy pass
    자바 for문
    jsp parameter
    AI 코딩 에이전트
    SSL 인증서
    lang rust
    docker
    nginx ssl 설정
    에디터 팁
    css transition
    API 설계
    React Compiler
    vscode
    자바 객체 지향
    클론코딩
    svelte
    nginx ssl 적용
    vue cli
    브라우저 자동화
    rust linux
    Extension Bisect
    css tb
    ubuntu
    vue 설치
    VS Code 팁
    Node
    spring java
    css list
    자바 클래스
    Java Array
    css float
    티스토리 자동화
    jsp include
    러스트
    servlet class
    css perspective
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
밍글링글링
[SPRING] 스프링과 마이바티스 에서 다중 데이타소스 사용하기
상단으로

티스토리툴바