티스토리 뷰





반응형

오늘은 간만에 List로 데이터를 불러오는 것을 해볼 것이다. 간략하게 진행할 것이니 생략되는 내용이 많을 것이다.

 

1. List를 이용해 데이터를 뿌려보자

 

index.jsp

1
2
<a href="${path }/selectList.do">리스트를 이용해 다중행 출력</a><br>
<a href="${path }/selectMap.do">Map을 이용해 다중행 출력</a><br>
cs

요렇게 간단하게 진행할 것이다.

 

1
2
3
4
5
6
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Student> list = service.selectList();
        
        request.setAttribute("list", list);
        request.getRequestDispatcher("/views/student/selectList.jsp").forward(request, response);
    }
cs

서블릿으로 이렇게 아무 매개변수가 없이 전체 데이터를 뽑아와 setAttribute에 넣어주고 페이지 전환했다.

바로 mapper로 넘어가 어떻게 데이터가 넘어오는지 분석하자!

 

dao

1
2
3
4
5
6
@Override
    public List<Student> selectList(SqlSession session) {
        List<Student> list = session.selectList("student.selectList");
        System.out.println(list);
        return list;
    }
cs

 

mapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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="student">    
        <select id="selectList" resultType="student">
            select student_no as studentNo, 
            student_name as studentName,
            student_addr as studentAddr,
            student_tel as studentTel,
            student_email as studentEmail,
            reg_date as redDate
            from student
        </select>
</mapper>
cs

제일 처음 select_no as studentNo 이런식으로 바꿔주는 이유는 앞에는 DB에 저장된 이름이고 뒤에는 자바의 student 객체에 멤버변수 이름이다. 그게 다르기 때문에 as로 그 이름을 맞춰줘야만 데이터가 알맞게 들어간다. 만약 DB와 객체 멤버변수 이름이 같다면 안해줘도 됨.

검색이라 select 태그를 사용하며 resultType은 return타입이라 생각하면 될 것 같다. 근데 우리는 dao에서 List<Student> list로 데이터를 받는다. 근데 mapper에서의 리턴값은 student다. 왜그럴까? 그 이유는 한 행을 객체로 보기때문에 한 행을 객체 student로 차곡차곡 담은 뒤 mybatis가 알아서 리스트로 넣어주기 때문이다. 애초에 설계가 그렇게 되어있다. (프레임워크가 원래 그렇다.)

 

전달 받은 데이터는 아래와같이 뿌려준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
 
    <c:forEach items="${list }" var="val" >
        ${val.studentNo }<br>
        ${val.studentName }<br>
        ${val.studentTel }<br>
        ${val.studentAddr }<br>
        ${val.studentEmail }<br>
        ${val.redDate }<br><br>
    </c:forEach>
    <c:if test="${empty list }">
        ${"데이터가 존재하지않아요."}
    </c:if>
    
</body>
</html>
cs

 

2. Map을 이용해 데이터를 뿌려보자.

 

1
2
3
4
5
6
7
8
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        List<Map<String,String>> list = service.selectMap();
        System.out.println(list);
        request.setAttribute("list", list);
        request.getRequestDispatcher("/views/student/selectList.jsp").forward(request, response);
        
    }
cs

Map도 List와 앞에는 똑같다. 바로 mapper로 넘어가자!

 

1
2
3
4
5
6
7
8
9
10
11
12
    <select id="selectMap" resultMap="selectMapList">    
        select * from student
    </select>
 
    <resultMap type="map" id="selectMapList">
        <result column="student_no" property="studentNo"/>
        <result column="student_name" property="studentName"/>
        <result column="student_tel" property="studentTel"/>
        <result column="student_Addr" property="studentAddr"/>
        <result column="student_email" property="studentEmail"/>
        <result column="reg_date" property="redDate"/>
    </resultMap>
cs

여기선 select로 검색은 따로하고 결과에 대한 처리는 resultMap에서 한다. 

select문과 id값을 맞춰준 상태에서 <resultMap type="map">을 하면 DB의 변수명 student_no를 studentNo라는 key에 넣는다. 

Student객체의 멤버변수와는 무관하게 저장하는 것이다.

 

첫 줄은 List로 받아온 값이고 2번째 줄은 Map으로 받아온 데이터다. 보시다시피 

첫 줄은 객체의 toString값이고 두번짼 key : value형식으로 가져온 데이터다. 위 처럼 새롭게 지정해서 가져올 수도 있고 6~11번째 줄을 아예 비워놓고 실행 시키면 DB에서 사용하는 이름 그대로 넘어온다. 단!! 사용할 땐 모두 대문자처리로 불러와야한다.

 

이제 데이터를 불러올 때 그 데이터를 담을 vo 객체는 필요가 없어서 더욱 편하게 사용이 가능할 것이다.

 

 

해당 게시글이 도움이 되셨다면 광고

 클릭한번 부탁드립니다 ㅎㅎ

 

 

 

 

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

반응형

'Back-end > Spring' 카테고리의 다른 글

Spring STS 설정 하기#1  (0) 2019.02.14
Spring STS 설치하기!!  (0) 2019.02.14
Mybatis 데이터 삽입하기  (0) 2019.02.02
Spring JSTL Formatting Tags  (0) 2019.02.01
Spring EL & JSTL  (0) 2019.01.30
댓글
반응형
최근에 달린 댓글
글 보관함
Total
Today
Yesterday
최근에 올라온 글
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30