Mybatis + Myabtis Spring 사용시 마이바티스 설정파일 사용법

2016. 11. 14. 15:52·Java/Spring
반응형

MyBatis를 Spring과 함께 사용할 경우, 기본 설정만으로도 대부분의 상황에 충분히 대응할 수 있습니다. 별도의 세부 설정이 필요한 경우를 제외하고는 디폴트 설정을 활용하는 편이 일반적입니다.

 

Spring에서는 MyBatis 설정을 자동으로 처리해주는 부분이 많기 때문에, SqlSessionFactoryBean에 mapper 위치 정도만 지정한 뒤 사용하는 경우가 잦습니다. 예를 들어, Spring의 기본 설정 파일을 아래와 같이 작성한 뒤, 매퍼 파일들을 resources/mapper 혹은 resources/mybatis와 같은 디렉토리에 배치할 수 있습니다. 여기서는 mapper 폴더 아래에 mybatis-config.xml을 두는 예시를 들어보겠습니다.

 

예시 설정 (mapper-config.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:mybatis="http://mybatis.org/schema/mybatis-spring"
       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">

    <!-- SqlSessionFactoryBean 설정 -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- MyBatis 기본 설정 파일 경로 지정 -->
        <property name="configLocation" value="classpath:/mapper/mybatis-config.xml"/>
        <!-- 매퍼 XML 파일 위치 지정 -->
        <property name="mapperLocations" value="classpath*:/mapper/**/*_SQL.xml"/>
    </bean>

    <!-- SqlSessionTemplate 설정 -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSession"/>
    </bean>

    <!-- 매퍼 인터페이스 자동 스캐닝 설정 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="매퍼 인터페이스들이 위치한 패키지 경로"/>
    </bean>

</beans>

 

위 설정을 통해 Spring은 mybatis-config.xml을 기본 설정으로 사용하고, 해당 설정을 기반으로 매퍼 XML 파일(*_SQL.xml)들을 자동으로 로딩합니다. 또한, MapperScannerConfigurer를 이용해 매퍼 인터페이스를 빈으로 등록하므로, @Autowired 등을 통해 손쉽게 매퍼를 주입받아 사용할 수 있습니다.

mybatis-config.xml 예시

아래는 classpath:/mapper 디렉토리 하위에 mybatis-config.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:mybatis="http://mybatis.org/schema/mybatis-spring"
       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">

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:/mapper/mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath*:/mapper/**/*_SQL.xml"/>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSession"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="매퍼 인터페이스 패키지"/>
    </bean>

    <!-- 타입 핸들러 등록 예시 -->
    <typeHandlers>
        <typeHandler handler="org.mybatis.example.ExampleTypeHandler"/>
    </typeHandlers>

</beans>

위와 같이 설정을 완료하면 Spring과 MyBatis를 연동하는 과정이 간소화되며, 기본 설정과 자동화된 매퍼 스캔 기능을 통해 빠르고 간편한 개발 환경을 구축할 수 있습니다.

반응형
저작자표시 (새창열림)

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

스프링 프로파일 (Spring profile) 을 통해 환경별로 다른 설정을 해보자  (0) 2016.11.24
Spring 내에서 리소스 불러오기  (0) 2016.11.18
스프링 Properties 파일을 이용해서 설정하기  (0) 2016.11.18
Tomcat 으로 원격 배포와 서버 원격디버깅  (0) 2016.07.18
Resource Handling in Spring MVC  (0) 2014.11.30
'Java/Spring' 카테고리의 다른 글
  • Spring 내에서 리소스 불러오기
  • 스프링 Properties 파일을 이용해서 설정하기
  • Tomcat 으로 원격 배포와 서버 원격디버깅
  • Resource Handling in Spring MVC
Ethan Kang
Ethan Kang
Digital nomad + Software Engineer
    반응형
  • Ethan Kang
    Software Engineer Ethan
    Ethan Kang
  • 전체
    오늘
    어제
    • Programming (105)
      • Java (22)
        • Spring Framework (6)
        • Spring (8)
        • Spring Security (0)
        • JPA (3)
        • MyBatis (1)
        • Servlet, JSP (2)
      • DevOps (4)
        • Kubernetes (2)
        • Docker (1)
        • Terraform (0)
        • Jenkins (0)
        • Bazel (1)
      • Front-End (18)
        • ReactJS (0)
        • Typescript (3)
        • JQuery (1)
        • Java Script (13)
        • RxJS (0)
        • CSS (1)
      • Messaging Queue (1)
        • Kafka (1)
      • Linux (Ubuntu based) (8)
        • Ubuntu (0)
        • CentOS (2)
        • Shell Scripting (2)
      • PHP (5)
        • Laravel (2)
        • PHP 문법 (3)
      • Go (1)
        • Basics (1)
      • Python (16)
        • Flask (1)
        • Django (4)
      • App Development (4)
        • Android (1)
        • Cordova (0)
        • React Native (0)
        • Hybrid Programming (2)
        • IOS (1)
      • Database (4)
        • SQL (0)
        • My SQL (4)
        • MongoDB (0)
      • Shader Programming (0)
      • Tools (5)
        • GIT (2)
      • C# (3)
        • ASP.NET MVC (2)
        • CSharp 파헤치기 (1)
      • 서평 (1)
      • ETC (4)
        • C++ (0)
        • Geo Server (0)
        • NodeJS2 (0)
        • Ruby (2)
        • Elastic Search (0)
        • Camera (0)
        • Open Source (2)
        • WebVR (0)
      • 소프트웨어 이론 (2)
        • TDD (1)
        • Architecture (1)
        • WEB DEV (0)
  • 블로그 메뉴

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

    • 컬러스크립터
  • 공지사항

    • 좋은 프로그래머가 되는 24가지 방법
  • 인기 글

  • 태그

    스프링
    mysql데이터복구
    자바
    Python
    java
    autoloading
    N+1
    mybatis
    spring
    스프링데이타
    db
    JPA
    이미지 #jsp
    django #장고
    데이터베이스
    데이터베이스캐쉬
    Kotlin
    psr-4
    mysql
    VersionControl
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Ethan Kang
Mybatis + Myabtis Spring 사용시 마이바티스 설정파일 사용법
상단으로

티스토리툴바