오늘이라도

[MyBatis] 17. 조건 검색 본문

취업성공패키지 SW 개발자 교육/Web

[MyBatis] 17. 조건 검색

upcake_ 2020. 6. 1. 09:25
반응형

 

https://github.com/upcake/Class_Examples

교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다. 

gif 파일은 클릭해서 보는 것이 정확합니다.


 - 조건 검색 -

<%@page import="com.hanul.study.MemberDTO"%>
<%@page import="java.util.List"%>
<%@page import="com.hanul.study.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("utf-8");
MemberDAO dao = new MemberDAO();
List<MemberDTO> list = dao.memberSearchAll();
pageContext.setAttribute("list", list);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>전체 회원 목록 조회</title>
<script type="text/javascript">
function fnDelete(id){
	//alert("id : " + id);
	if(confirm("정말 삭제하시겠습니까?")) {
		location.href="memberDelete.jsp?id=" + id;
		//Get 방식으로 정보를 넘길때 띄어쓰기 안하게 주의할 것
	}
}
</script>
</head>
<body>
<div align="center">
	<h3>전체 회원 목록 조회</h3>
	<table border="1" width="80%">
		<tr>
			<th>이름</th>
			<th>아이디</th>
			<th>비밀번호</th>
			<th>나이</th>
			<th>주소</th>
			<th>전화번호</th>
			<th>삭제</th>
			<th>수정</th>
		</tr>
		<!-- for문을 이용한 출력 -->
		<%--
			for(int i = 0; i < list.size(); i++) {
				out.println("<tr align='center'>");
					out.println("<td>" + list.get(i).getIrum() + "</td>");
					out.println("<td>" + list.get(i).getId() + "</td>");
					out.println("<td>" + list.get(i).getPw() + "</td>");
					out.println("<td>" + list.get(i).getAge() + "</td>");
					out.println("<td>" + list.get(i).getAddr() + "</td>");
					out.println("<td>" + list.get(i).getIrum() + "</td>");
				out.println("</tr>");
			}
		--%>
		<!-- ---------------------------------------------------------------------------------------- -->
		<!-- 향상된 for문을 이용한 출력 -->
		<%--
			for(MemberDTO dto : list) {
				out.println("<tr align='center'>");
				out.println("<td>" + dto.getIrum() + "</td>");
				out.println("<td>" + dto.getId() + "</td>");
				out.println("<td>" + dto.getPw() + "</td>");
				out.println("<td>" + dto.getAge() + "</td>");
				out.println("<td>" + dto.getAddr() + "</td>");
				out.println("<td>" + dto.getTel() + "</td>");
				out.println("</tr>");
			}
		--%>
		<!-- ---------------------------------------------------------------------------------------- -->
		<!-- JSTL을 이용한 출력 -->
		<c:forEach var="i" items="${list }">
			<tr align="center">
				<td>${i.irum }</td>
				<td>${i.id }</td>
				<td>${i.pw }</td>
				<td>${i.age }</td>
				<td>${i.addr }</td>
				<td>${i.tel }</td>
				<td><input type="button" value="삭제" onclick="fnDelete('${i.id }')"/></td>
				<!-- id값을 넘길때 따옴표로 묶어줘야 문자를 입력해도 오류가 안난다. -->
				<td><input type="button" value="수정" onclick="location.href='memberDetail.jsp?id=${i.id}'"/></td>
			</tr>
		</c:forEach>
		<tr align="center">
			<td colspan="8">
				<form action="memberSearch.jsp" method="post"> 
					<select name="part">
						<option value="irum">이름</option>
						<option value="id">아이디</option>
						<option value="addr">주소</option>
						<option value="tel">전화번호</option>
					</select>
					<input type="text" name="searchData" required="required" />
					<input type="submit" value="검색하기" />
					<input type="button" value="회원가입" onclick="location.href='MemberMain.html'"/>
				</form>
			</td>
		</tr>
	</table>
</div>
</body>
</html>

▲memberList.jsp

 

<%@page import="java.util.List"%>
<%@page import="com.hanul.study.MemberDTO"%>
<%@page import="com.hanul.study.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
request.setCharacterEncoding("utf-8");
String part = request.getParameter("part");
String searchData = request.getParameter("searchData");
//System.out.println(part);
//System.out.println(searchData);

MemberDAO dao = new MemberDAO();
List<MemberDTO> list = dao.memberSearch(part, searchData);
pageContext.setAttribute("list", list);	//바인딩 객체
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>memberSearch</title>
<script type="text/javascript">
function fnDelete(id){
	//alert("id : " + id);
	if(confirm("정말 삭제하시겠습니까?")) {
		location.href="memberDelete.jsp?id=" + id;
		//Get 방식으로 정보를 넘길때 띄어쓰기 안하게 주의할 것
	}
}
</script>
</head>
<body>
<div align="center">
	<h3>검색 결과 보기</h3>
	<table border="1" width="80%">
		<tr>
			<th>이름</th>
			<th>아이디</th>
			<th>비밀번호</th>
			<th>나이</th>
			<th>주소</th>
			<th>전화번호</th>
			<th>삭제</th>
			<th>수정</th>
		</tr>
		<%if(list.size() == 0) { //검색 결과가 없으면%>
			<tr align="center">
				<td colspan="8">검색 결과가 없습니다.</td>
			</tr>
		<%} %>
		<c:forEach var="i" items="${list }">
			<tr align="center">
				<td>${i.irum }</td>
				<td>${i.id }</td>
				<td>${i.pw }</td>
				<td>${i.age }</td>
				<td>${i.addr }</td>
				<td>${i.tel }</td>
				<td><input type="button" value="삭제" onclick="fnDelete('${i.id }')"/></td>
				<!-- id값을 넘길때 따옴표로 묶어줘야 문자를 입력해도 오류가 안난다. -->
				<td><input type="button" value="수정" onclick="location.href='memberDetail.jsp?id=${i.id}'"/></td>
			</tr>
		</c:forEach>
		<tr align="center">
			<td colspan="8">
				<input type="button" value="전체 회원 목록 보기" onclick="location.href='memberList.jsp'" />
				<input type="button" value="회원가입" onclick="location.href='MemberMain.html'"/>
			</td>
		</tr>
	</table>
</div>
</body>
</html>

▲memberSearch.jsp

 

▼MemberDAO.java : 조건 검색 메서드

	//조건 검색
	public List<MemberDTO> memberSearch(String part, String searchData) {
		SqlSession session = sqlMapper.openSession();
		SearchDTO dto = new SearchDTO();
		dto.setPart(part);
		dto.setSearchData("%" + searchData + "%");	// LIKE절에 사용하기 때문에 앞뒤에 %%를 붙여준다.
		List<MemberDTO> list = null;
		list = session.selectList("memberSearch", dto);
		session.close();
		return list;
	}//memberSearch()
} //class

 

▼MemberDAO.java : 전문

더보기
package com.hanul.study;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MemberDAO {
	//기존 JDBC 모델에서는 Connection(DB 연결)을 먼저 만들었지만,
	//myBatis 경우 SqlSessionFactory 객체를 먼저 생성
	private static SqlSessionFactory sqlMapper;
	//스태틱 블록(초기화 블록) : 가장 먼저, 단 한번만 실행 되는 블록
	static {
		String resource = "com/hanul/mybatis/SqlMapConfig.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlMapper = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SqlSessionFactory Exception!!!");
		}
	} //static
	
	//회원 가입
	public int memberInsert(MemberDTO dto) {
		//SqlSessionFactory(sqlMapper)에서 session 활성화
		SqlSession session = sqlMapper.openSession();
		int succ = 0;
		succ = session.insert("memberInsert", dto); //insert SQL insert 쿼리 : memberMapper.xml
		session.commit();	//커밋
		session.close();	//session 비활성화
		return succ;
	} //memberInsert()
	
	//전체 회원 검색
	public List<MemberDTO> memberSearchAll() {
		SqlSession session = sqlMapper.openSession();
		//myBatis에서는 ArrayList가 아닌 List를 사용한다
		List<MemberDTO> list = null;
		//파라미터에 식별자 이름을 적는다. 
		list = session.selectList("memberSearchAll");
		session.close();
		return list;
	} //memberSearchAll()
	
	//회원 삭제
	public int memberDelete(String id) {
		SqlSession session = sqlMapper.openSession();
		int succ = 0;
		succ = session.delete("memberDelete", id);
		session.commit();
		session.close();
		return succ;
	} //memberDelete()
	
	//ID 검색
	public MemberDTO getById(String id) {
		SqlSession session = sqlMapper.openSession();
		MemberDTO dto = null;
		//정보를 하나만 받을 때는 selectOne 사용
		dto = session.selectOne("getById", id);
		session.close();
		return dto;
	} //getById()
	
	//회원 정보 수정
	public int memberUpdate(MemberDTO dto) {
		SqlSession session = sqlMapper.openSession();
		int succ = 0;
		succ = session.update("memberUpdate", dto);
		session.commit();
		session.close();
		return succ;
	} //memberUpdate()
	
	//조건 검색
	public List<MemberDTO> memberSearch(String part, String searchData) {
		SqlSession session = sqlMapper.openSession();
		SearchDTO dto = new SearchDTO();
		dto.setPart(part);
		dto.setSearchData("%" + searchData + "%");	// LIKE절에 사용하기 때문에 앞뒤에 %%를 붙여준다.
		List<MemberDTO> list = null;
		list = session.selectList("memberSearch", dto);
		session.close();
		return list;
	}//memberSearch()
} //class

 

▼SearchDTO.java

package com.hanul.study;

import java.io.Serializable;

public class SearchDTO implements Serializable{
	private String part, searchData;
	
	public SearchDTO() {}

	public SearchDTO(String part, String searchData) {
		super();
		this.part = part;
		this.searchData = searchData;
	}

	public String getPart() {
		return part;
	}

	public void setPart(String part) {
		this.part = part;
	}

	public String getSearchData() {
		return searchData;
	}

	public void setSearchData(String searchData) {
		this.searchData = searchData;
	}
	
	
}

 

▼SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- db.properties의 경로를 지정해준다. -->
	<!-- resource 속성은 .이 아닌 /로 접근한다. -->
	<properties resource="com/hanul/mybatis/db.properties" />
	
	<!-- 특정 클래스의 별칭(alias)을 지정 -->
	<typeAliases>
		<typeAlias type="com.hanul.study.MemberDTO" alias="MemberDTO"/>
		<typeAlias type="com.hanul.study.SearchDTO" alias="SearchDTO"/>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<!-- Mapper 경로 지정 -->
	<mappers>
		<mapper resource="com/hanul/mybatis/memberMapper.xml" />
	</mappers>
</configuration>

 

▼memberMapper.xml

<?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="com.hanul.mybatis.memberMapper.xml">
	<!-- SQL 문장 작성 -->
	<!-- 
		<insert | delete | update | select 속성="값" 속성="값 ~~>
			- id 속성 : DAO에서 설정한 값 ▶ session.insert("memberInsert", dto);
			- parameterType 속성 : 매개 변수 타입(클래스타입, 기본데이터타입) : 생략 가능
			- 입력 값 표기 : dto.getIrum() → #{dto 內 속성명} ▶ #{irum}
			- SQL 문장의 마지막에 세미콜론(;)은 입력하지 않는다. 
			- resultType 속성 : select 쿼리를 수행했을 때 결과 타입
		</insert | delete | update | select>
	 -->
	 <!-- id에는 DAO에서 정한 메서드 이름을 적는다. -->
	 <!-- 여기서 MemberDTO는 SqlMapConfig에서 지정한 alias이다. -->
	 <insert id="memberInsert" parameterType="MemberDTO">
	 	INSERT INTO member VALUES(#{irum}, #{id}, #{pw}, #{age}, #{addr}, #{tel})
	 </insert>
	 
	 <!-- 가져오는 칼럼이 MemberDTO 타입 -->
	 <select id="memberSearchAll" resultType="MemberDTO">
	 	SELECT * FROM member
	 </select>
	 
	 <delete id="memberDelete" parameterType="String">
	 	DELETE FROM member WHERE id = #{id}
	 </delete>
	 
	 <select id="getById" parameterType="String" resultType="MemberDTO">
	 	SELECT * FROM member WHERE id = #{id}
	 </select>
	 
	  <update id="memberUpdate" parameterType="MemberDTO">
	 	UPDATE member SET irum = #{irum}, pw = #{pw}, age = #{age},
	 						 addr = #{addr}, tel = #{tel} WHERE id = #{id} 
	 </update>
	 
	 <select id="memberSearch" parameterType="SearchDTO" resultType="MemberDTO">
	 	SELECT * FROM member WHERE UPPER(${part}) LIKE UPPER(#{searchData})
	 	<!-- SELECT * FROM member WHERE #{part} LIKE #{searchData} -->
	 	<!-- #{part}는 네임값이라 검색 결과가 나오지 않는다 ${part} (EL)는 밸류값이라 정상적으로 나옴 -->
	 </select>
	
</mapper>

 

반응형