ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • spring에서 mybatis 연동 완벽 작동! spring mybatis 연동 방법
    자바웹프로그래밍/mybatis 2023. 2. 2. 23:33
    728x90
    반응형

    *도움이 되셨다면 광고 클릭 한번 부탁드립니다. (__)

     

    1.pom.xml 에 종속 라이브러리 추가

    		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    		<dependency>
    			<groupId>org.mybatis</groupId>
    			<artifactId>mybatis-spring</artifactId>
    			<version>2.0.7</version>
    		</dependency>
    
    		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    		<dependency>
    			<groupId>org.mybatis</groupId>
    			<artifactId>mybatis</artifactId>
    			<version>3.5.6</version>
    		</dependency>

     

    2.root-context.xml (bean을 등록 하는곳) 

    *spring에서 @configuration 으로 등록하는 방법이 있지만, 여기서는 xml에서만 등록하는 법을 소개하겠다. 어차피 xml에서 bean을 등록하나 @configuration에서 bean을 등록하나 같은원리이므로..

     

    2-1 일단 jdbc를 사용하기위한 datasource와 mybatis에서 제공하는 sqlSessionFactory를 bean으로 등록해준다. 

    mybatis는 *Mapper.xml 파일을 이용하여 쿼리문을 작성한다. (잠시후 소개할 Mapper interface에서 쿼리문을 작성할수도있음. 하지만 여기서 다루지는 않겠다.) 그래서 *Mapper.xml를 search하기위해 mapperLocations 속성을 주입해준다.

     

    <!-- springframework의 DriverManagerDataSource를 이용하여 dataSource 설정 -->
    	<bean id="doDataSource"
    		class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    		p:driverClassName="org.postgresql.Driver" 
    		p:url="jdbc:postgresql://127.0.0.1:5432/vidb"
    		p:username="root" 
    		p:password="root" 
    	/>
    
    	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<property name="dataSource" ref ="doDataSource"></property>
    		<property name="mapperLocations" value="classpath:mapper/**/*Mapper.xml"></property>
    	</bean>

    2-1-1 *Mapper.xml 을 생성해준다. 필자는 mapper 폴더를 생성하고 그안에 *Mapper.xml 을 생성해주었다.

     

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="kr.co.example.mapper.PolicyMapper">
    
        <select id="selectListCompany" parameterType="Map" resultType="HashMap">
            select
            company_code,company_name,company_ecode
            from
            company_list
            where 1=1
            <if test="searchKeyword != null and searchKeyword !=''">
                and
                (company_name ilike #{searchKeyword}
                or
                company_ecode ilike #{searchKeyword})
            </if>
            <if test="sort_field != null and sort_field != '' " >
                order by #{sort_field} #{sort_dir}
            </if>
            limit #{length}::int4 offset #{start}::int4
        </select>
    
    
    </mapper>

    policyMapper.xml

     

     

     

    2-2 interface로 Mapper 생성 mapper.xml 과 연결될 mapper inteface이다. mapper.xml에 쿼리 id와 interface mapper method 명이 같아야한다.

    예) mapper.xml select id="selectListCompany" , interface mapper method =" selectListCompany(Map<String,String> param)" 

     

     

    /**
     * \* Created with JIRANDATA.
     * \* @author: kim-dong-wan
     * \* Date: 2023/02/01
     * \* Time: 1:06 오후
     * \* Description:
     * \
     */
    
    public interface PolicyMapper {
        List<Map<String,Object>> selectListCompany(Map<String,String> param);
       
    
    }

    poilicyMapper.java

     

     

    2-3 mapper interface를 bean으로 등록해주기 위한 component-scan 등록

     

      '  xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"',

    'http://mybatis.org/schema/mybatis-spring '

    'http://mybatis.org/schema/mybatis-spring.xsd'

     

    위 세개를 root-context.xml(main applicationContext.xml) 맨위에 xmlns 선언해주는곳에 넣어준다.

    <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:context="http://www.springframework.org/schema/context"
    	   xmlns:task="http://www.springframework.org/schema/task"
    	   xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
    	   xmlns:tx="http://www.springframework.org/schema/tx"
    	   xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    	   xsi:schemaLocation="http://www.springframework.org/schema/beans
     						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    						http://www.springframework.org/schema/context
    						http://www.springframework.org/schema/context/spring-context-3.0.xsd
    						http://www.springframework.org/schema/util
    						http://www.springframework.org/schema/util/spring-util.xsd
    						http://www.springframework.org/schema/tx
    						http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    						http://www.springframework.org/schema/aop
    					    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    					    http://www.springframework.org/schema/task 
    						http://www.springframework.org/schema/task/spring-task.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

     

    2-4 mybais:scan을 통한 mapper scan (exmaple.mapper 패키지 안에있는 mapper종류들을 전부 bean으로 만들어준다.)

     

    	<!-- scan mybatis mapper-->
    	<mybatis:scan base-package="kr.co.example.mapper"/>

     

     

    3.TEST

     

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(locations="../resources/config/applicationContext.xml")
    public class PolicyDAOImpTest {
    
    
        //PolicyMapper policyMapper;
        @Autowired
        private DataSource doDataSource;
    
        @Autowired
        private SqlSessionFactory sqlSessionFactory;
    
        @Autowired
        private PolicyMapper policyMapper;
    
        @Test
        public void testMybatis(){
            SqlSession session = sqlSessionFactory.openSession();
            try {
                Connection con = doDataSource.getConnection();
    
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
        }
    
        @Test
        public void testPolicyMapper(){
            Map<String,String> param = new HashMap<String,String>();
            param.put("length","2");
            param.put("start","1");
            List<Map<String,Object>> rList = policyMapper.selectListCompany(param);
            assertNotEquals(rList.size(),0);
        }
    
    }

     

    728x90
    반응형
Designed by Tistory.