본문 바로가기
Java/└ Mybatis

Mybatis) resultMap 사용하기

by 박채니 2022. 8. 8.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


<select id="selectOneStudent" resultType="student">
    select * from student where deleted_at is null and no = #{no}
</select>

 

resultMap으로 변환

<select id="selectOneStudent" resultMap="studentDtoMap">
    select * from student where deleted_at is null and no = #{no}
</select>

<resultMap type="student" id="studentDtoMap"> <!-- 반환타입 : student -->
    <!-- 예측 가능한 범주일 때는 생략 가능! -->
    <id column="no" property="no"/> <!-- <id> : PK컬럼! -->
    <result column="name" property="name"/>
    <result column="tel" property="tel"/>
    <result column="created_at" property="createdAt"/> <!-- column은 대소문자 구분 X, property는 대소문자 구분 O -->
    <result column="updated_at" property="updatedAt"/>
    <result column="deleted_at" property="createdAt"/>
</resultMap>


resultType이 Map인 경우

 

url-command.properties

/student/studentMap.do = com.ce.app.student.controller.StudentMapController

 

Controller

StudentMapController

@Log4j
@RequiredArgsConstructor
public class StudentMapController extends AbstractController {
	private final StudentService studentService;
	
	@Override
	public String doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int no = Integer.parseInt(request.getParameter("no"));
		Map<String, Object> map = studentService.selectOneStudentMap(no);
		log.debug("map = " + map);
		
		response.setContentType("application/json; charset=utf-8");
		new Gson().toJson(map, response.getWriter());
		
		return null;
	}
}

@콘솔출력값
2022-08-08 14:32:10 DEBUG StudentMapController:26 - map = {NO=2, CREATED_AT=2022-08-04 21:11:16.0, TEL=01011112222, UPDATED_AT=2022-08-08 12:27:22.0, NAME=신사임둥}

 

Service

StudentServiceImpl

(interface 생략)

@Override
public Map<String, Object> selectOneStudentMap(int no) {
    try(SqlSession sqlSession = getSqlSession()) {
        return studentDao.selectOneStudentMap(sqlSession, no);			
    }
}


Dao

StudentDaoImpl

(interface 생략)

@Override
public Map<String, Object> selectOneStudentMap(SqlSession sqlSession, int no) {
    return sqlSession.selectOne("student.selectOneStudentMap", no);
}

 

student-mapper.xml

<select id="selectOneStudentMap" resultType="map">
    select * from student where deleted_at is null and no = #{no}
</select>

 

selectOne.jsp

	<div id="student-container">
		<h2>학생정보 검색</h2>
		<p>등록된 학생 수는 <span id="totalCount">${totalCount}</span>명입니다.</p>
		<form name="studentSearchFrm">
			<table class="tbl-student">
				<tr>
					<th>학생번호</th>
					<td>
						<input type="number" name="no" value="" required/>
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="검색" />
					</td>
				</tr>
			</table>
		</form>
		
		<hr />
		
        <h2>학생 정보 수정</h2>
        <form name="studentUpdateFrm">
            <table class="tbl-student">
                <tr>
                    <th>학생번호</th>
                    <td>
                        <input type="number" name="no" required readonly/>
                    </td>
                </tr>
                <tr>
                    <th>학생이름</th>
                    <td>
                        <input type="text" name="name" required/>
                    </td>
                </tr>
                <tr>
                    <th>학생전화번호</th>
                    <td>
                        <input type="tel" name="tel"  required/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="button" value="수정" onclick="updateStudent();"/>
                        <input type="button" value="삭제" onclick="deleteStudent();" />
                    </td>
                </tr>
            </table>
        </form>
	</div>
	
<script>
document.studentSearchFrm.addEventListener('submit', (e) => {
	e.preventDefault();
	
	const no = e.target.no.value;
	
	$.ajax({
		//url : "${pageContext.request.contextPath}/student/student.do",
		url : "${pageContext.request.contextPath}/student/studentMap.do",
		data : {no},
		success(student) {
			const frm = document.studentUpdateFrm;
			if(student) {
				console.log(student);
				const {no, name, tel} = student;
				frm.no.value = no;
				frm.name.value = name;
				frm.tel.value = tel;
			} else {
				alert("조회한 학생이 존재하지 않습니다.");
				frm.reset();
			}
		},
		error : console.log
	});
});

학생 이름, 전화번호에는 undefined가 출력되는 것을 확인할 수 있으며, 전달 받은 값을 확인해보면 key 값이 "CREATED_AT", "NAME"... 인 것을 확인할 수 있습니다.

이는 resultType="map"으로 (java.util.Map) 설정하였기 때문에 컬럼명을 그대로 key값으로 사용했기 때문이죠.

이처럼 사용해야 하는 key값이 별도로 있다면 resultMap을 이용해주어야 합니다.

 

resultMap 사용 시 (student-mapper.xml 제외 모든 코드 동일)

<select id="selectOneStudentMap" resultMap="studentMap">
    select * from student where deleted_at is null and no = #{no}
</select>

<resultMap type="map" id="studentMap">
    <id column="no" property="no"/>
    <result column="name" property="name"/>
    <result column="tel" property="tel"/>
    <result column="created_at" property="createdAt"/>
    <result column="updated_at" property="updatedAt"/>
    <result column="deleted_at" property="deletedAt"/>
</resultMap>

지정한 property로 key값이 지정되어 출력되는 것을 확인할 수 있습니다.