MyBatis :: mapper 설정

김병철·2022년 11월 25일
0

mybatis

목록 보기
3/4

mapper 설정

'resources'폴더 안에 'mappers'폴더 생성 후 그 안에 식별하기 쉬운 이름으로 파일을 등록한다.

# xxxxx-mapper.xml 작성

xml 최상단에 아래와 같이 xml형식을 지정하여 이하의 설정 내용이 MyBatis mapper 설정임을 선언

<?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 태그 :

mapper 태그를 작성하고 외부에서 접근할 수 있는 이름인 namespace속성을 기입하고,

이후에 작성될 태그들은 mapper 안에 기록한다.

<mapper namespace="memberMapper">
	<!-- mapper 내부에 작성될 내용 -->
</mapper>
  • resultMap 태그 :

조회한 결과를 객체와 Row간 1:1 매칭이 아닌, 원하는 객체의 필드에 담아 반환할 때 사용한다.

<resultMap type="member" id="memberResult">
	<result column="USER_NO" property="userNo"/>
 	<result column="USER_ID" property="userId"/>
  	<result column="USER_PWD" property="userPwd"/>
  	<result column="USER_NAME" property="userName"/>
  	<result column="EMAIL" property="email"/>
  	<result column="BIRTHDAY" property="birthday"/>
  	<result column="GENDER" property="gender"/>
  	<result column="PHONE" property="phone"/>
  	<result column="ADDRESS" property="address"/>
  	<result column="ENROLL_DATE" property="enrollDate"/>
  	<result column="MODIFY_DATE" property="modifyDate"/>
  	<result column="STATUS" property="status"/>	
</resultMap>

resultMap 태그의 type속성은 실제로 구현해 놓은 자바 POJO 객체를 사용해야 하며, mybatis-config.xml에서 typeAlias를 지정하지 않은 경우 패키지 명부터 클래스명까지 모두 기술해야 한다.

  • select 태그 :

sql의 조회구문을 작성할 때 사용되는 태그, 해당 쿼리를 외부에서 접근하고자 할 때 namespace.id명을 적어 접근 가능하다.

<select id="selectMember" resultMap="memberResult" parameterType="member">
	SELECT * 
	FROM MEMBER 
	WHERE USER_ID=#{userId} 
		AND USER_PWD=#{userPwd}
		AND STATUS = 'Y'
</select>
  • select 태그의 주요 속성 :
    • id : 구문을 찾기 위해 사용될 수 있는 namespace 내 유일한 구분자
    • parameterType : 구문에 전달될 파라미터의 클래스명(패키지 경로 포함)이나 별칭
    • resultType : 리턴되는 타입의 패키지 경로를 포함한 전체 클래스 명이나 별칭(collection인 경우 list, arraylist로 설정 가능)
    • resultMap : 리턴되는 타입의 필드명이 다를 때 사용하며 직접 이름을 지정하여 매칭

-resultMap과 resultType은 둘 모두를 사용할 수 없으면 둘 중 하나만 선언해야 한다.

  • insert, update, delete 태그 :

해당 태그들은 설정이 동일하다.

파라미터로 객체를 받는 경우 해당 객체의 필드값을 '변수명 = 값'의 Map 방식으로 조회하여 가져올 수 있다.

<insert id="insertMember" parameterType="member">
	INSERT INTO MEMBER (USER_NO, USER_ID, USER_PWD, USER_NAME, EMAIL, BIRTHDAY, GENDER, PHONE, ADDRESS)
	VALUES (SEQ_UNO.NEXTVAL, #{userId}, #{userPwd}, #{userName}, #{email}, #{birthday}, #{gender}, #{phone}, #{address})
</insert>
profile
keep going on~

0개의 댓글