본문 바로가기
Develop/Spring

[06.스프링+MyBatis]3.XML Mapper의 작성

by jaekk 2018. 8. 17.

Mapper 

SQL문을 저장하는 존재

DAO클래스를 사용하는 SQL을 작성해야함

-XML

-인터페이스

사용 가능



XML을 사용하는 경우

XML로 작성된 mapper의 위치(저장 경로) 결정

XML Mapper 파일을 작성하고 필요한 DTD 추가

SQL 작성





1. Mapper 파일의 저장 경로

Java로 작성된 클래스와 경로를 분리하는 것이 유지보수에 좋음

1) src>main>resources> mappers폴더 생성



2. XML Mapper의 작성

src>main>java>resouces>mappers>memberMapper.xml 생성


http://www.mybatis.org/mybatis-3/ko/getting-started.html 을 참고하여 DTD작성 



1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.zerock.mapper.MemberMapper">
  <select id="getTime" resultType="string">
    select now()
  </select>
  <insert id="insertMember"    >
  insert into tbl_member (userid,userpw, username, email) values (#{userid},#{userpw},#{username},#{email})
  </insert>
</mapper>
cs

namepace

Mybatis에서 원하는 SQL문을 찾아 실행할 때 동작





3. myBatis-Spring에서 XML Mapper 인식

MyBatis가 동작하면 XML Mapper를 인식해야 한다.

root-context.xml 설정 변경



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
        
        
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1:3307/book_ex?useSSL=false"></property>
        <property name="username" value="zerock"></property>
        <property name="password" value="zerock"></property>
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" /
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property>
    </bean>
</beans>
 
cs



sqlSessionFactory에 mapperLocations 속성 추가

1
<property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property>
cs

작성된 mappers폴더 내 어떤 폴더와 관계없이 파일의 이름이 Mapper.xml로 끝나면 자동 인식









※ 본 게시글은 코드로 배우는 스프링 웹 프로젝트 책을 참고하여 작성하였습니다.

댓글