ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링 4.0 - myBatis 연동
    웹프로그래밍/spring 2018. 8. 2. 20:02


    스프링에서 MyBatis 연동하기


    1. 모듈추가

         <!-- MyBatis -->

            <dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis</artifactId>

    <version>3.2.3</version>

    </dependency>

            

            <dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis-spring</artifactId>

    <version>1.2.2</version>

    </dependency>


         <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-context-support</artifactId>

                <version>${org.springframework-version}</version>

            </dependency>

     

            <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-jdbc</artifactId>

                <version>${org.springframework-version}</version>

            </dependency>



    2.SqlSessionFactoryBean과 트랜잭션 관리자 설정

    SqlSessionFactoryBean으로 mybatis의 SqlSessionFactory를 생성한다.

    <?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: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="mapperLocations" value="classpath:/sqlMapper/*_SQL.xml" />

    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">

            <constructor-arg index="0" ref="sqlSession"/>

        </bean>  

    </beans>


    3. SqlSessionTemplate를 생성자나 프로퍼티로 전달받는 DAO 클래스 구현

    public class AbstractDAO {

    @Autowired

    private SqlSessionTemplate sqlSession;



    public Object insert(String queryId) {

    printQueryId(queryId);

    return sqlSession.insert(queryId);

    }

    }