본문 바로가기
Java/└ Mybatis

Mybatis) 검색 기능 추가하기

by 박채니 2022. 8. 10.

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

 

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


검색 기능 추가하기

 

Controller

EmpSearchController1

@Log4j
@RequiredArgsConstructor
public class EmpSearchController1 extends AbstractController {
	private final EmpService empService;
	
	@Override
	public String doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 사용자 입력값 처리
		String searchType = request.getParameter("searchType");
		String searchKeyword = request.getParameter("searchKeyword");
		Map<String, Object> param = new HashMap<>();
		param.put("searchType", searchType);
		param.put("searchKeyword", searchKeyword);
		log.debug("param = " + param);
		
		List<Map<String, Object>> list = null;
		
		// 2. 업무로직
		if(searchType != null && searchKeyword != null) {
			list = empService.search1(param);
		} else {
			list = empService.selectEmpList();
		}
		
		log.debug("list = " + list);
		request.setAttribute("list", list);
		
		return "emp/search1";
	}
}

검색을 하지 않았을 경우에는 searchType, searchKeyword가 모두 null 이기 때문에 분기처리를 통해 리스트를 가져와줍니다.

만일 존재한다면 검색 결과를 리턴해주고, 존재하지 않다면 전체 리스트를 조회하여 리턴해줍니다.

 

Service

EmpServiceImpl

(interface 생략)

@RequiredArgsConstructor
public class EmpServiceImpl implements EmpService {
	private final EmpDao empDao;
	
	@Override
	public List<Map<String, Object>> selectEmpList() {
		try(SqlSession sqlSession = getSqlSession()) {
			return empDao.selectEmpList(sqlSession);			
		}
	}
	
	@Override
	public List<Map<String, Object>> search1(Map<String, Object> param) {
		try(SqlSession sqlSession = getSqlSession()) {
			return empDao.search1(sqlSession, param);			
		}
	}
}

 

Dao

EmpDaoImpl

(interface 생략)

public class EmpDaoImpl implements EmpDao {
	@Override
	public List<Map<String, Object>> selectEmpList(SqlSession sqlSession) {
		return sqlSession.selectList("emp.selectEmpList");
	}
	
	@Override
	public List<Map<String, Object>> search1(SqlSession sqlSession, Map<String, Object> param) {
		return sqlSession.selectList("emp.search1", param);
	}
}

 

emp-mapper.xml

<mapper namespace="emp"> 
	<select id="selectEmpList" resultMap="empMap">
		select * from emp
	</select>
	
	<select id="search1" resultMap="empMap">
		select * from emp where ${searchType} like '%' || #{searchKeyword} || '%'
	</select>
	
	
	<resultMap type="map" id="empMap">
		<id column="emp_id" property="empId"/>
		<result column="emp_name" property="empName"/>
		<result column="emp_no" property="empNo"/>
		<result column="email" property="email"/>
		<result column="phone" property="phone"/>
		<result column="dept_code" property="deptCode"/>
		<result column="job_code" property="jobCode"/>
		<result column="sal_level" property="salLevel"/>
		<result column="salary" property="salary"/>
		<result column="bonus" property="bonus"/>
		<result column="manager_id" property="managerId"/>
		<result column="hire_date" property="hireDate"/>
		<result column="quit_date" property="quitDate"/>
	</resultMap>
</mapper>

${컬럼명 또는 테이블명} : 검색할 컬럼명 혹은 테이블명이 동적인 경우 사용

#{필드명} : ?로 치환되며, 동적인 값을 DB 저장 시 사용

 

※ 관련 참고 포스팅

https://back-end-developer.tistory.com/entry/MyBatis-mapperxml-%EC%9E%91%EC%84%B1%EB%B2%95-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0?category=822627 

 

[MyBatis] mapper.xml 작성법 알아보기

MyBatis의 mapper 속성의 특징 - #{필드명} : ?로 치환되고 preparedStatement 객체로 실행 동적인 값을 DB에 저장할때는 반드시 #{필드명} 사용해야함 - ${컬럼명 또는 테이블명} : DB에 저장하거나..

back-end-developer.tistory.com

 

search1.jsp

<%@ 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"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mybatis실습</title>
<style>
div#emp-container{text-align:center;}
table.tbl-emp{
	margin:0 auto;
	border:1px solid; 
	border-collapse:collapse;
}
table.tbl-emp th, table.tbl-emp td{
	border:1px solid;
	padding:5px;
}
div#search-container{
	padding:15px 0;
}
</style>
</head>
<body>
<div id="emp-container">
	<h2>사원정보 </h2>
	<div id="search-container">
		<form name="empSearchFrm">
			<select name="searchType" required>
				<option value="">검색타입</option>
				<!-- required여부를 판단할 value="" 반드시 있어야함.-->
			    <option value="emp_id" ${param.searchType eq 'emp_id' ? 'selected' : ''}>사번</option>
                <option value="emp_name" ${param.searchType eq 'emp_name' ? 'selected' : ''}>사원명</option>
                <option value="email" ${param.searchType eq 'email' ? 'selected' : ''}>이메일</option>
                <option value="phone" ${param.searchType eq 'phone' ? 'selected' : ''}>전화번호</option>
			</select>
			<input type="search" name="searchKeyword" value="${param.searchKeyword}" required />
			<input type="submit" value="검색" />
		</form>
	</div>
	
	<table class="tbl-emp">
		<tr>
			<th></th><!-- 1부터 넘버링 처리 -->
			<th>사번</th>
			<th>사원명</th>
			<th>주민번호</th><!--뒷6자리는 ******처리-->
			<th>이메일</th>
			<th>전화번호</th>
			<th>부서코드</th>
			<th>직급코드</th>
			<th>급여레벨</th>
			<th>급여</th><!--원화기호, 세자리마다 콤마표시-->
			<th>보너스율</th><!--percent로 표시-->
			<th>매니져 사번</th>
			<th>입사일</th><!--날짜형식 yyyy/MM/dd-->
			<th>퇴사여부</th>
		</tr>
		<!-- 조회된 데이터가 있는 경우와 없는 경우를 분기처리 하세요 -->
		<c:if test="${empty list}">
			<tr>
				<td colspan="14">조회된 정보가 없습니다.</td>
			</tr>
		</c:if>
		<c:if test="${!empty list}">
			<c:forEach items="${list}" var="emp" varStatus="vs">
				<tr>
					<td>${vs.count}</td>
					<td>${emp.empId}</td>
					<td>${emp.empName}</td>
					<td>
						${fn:substring(emp.empNo, 0, 8)}******
					</td>
					<td>${emp.email}</td>
					<td>${emp.phone}</td>
					<td>${emp.deptCode}</td>
					<td>${emp.jobCode}</td>
					<td>${emp.salLevel}</td>
					<td>
						<fmt:formatNumber value="${emp.salary}" type="currency"/>
					</td>
					<td>
						<fmt:formatNumber value="${emp.bonus}" type="percent"/>
					</td>
					<td>${emp.managerId}</td>
					<td>
						<fmt:formatDate value="${emp.hireDate}" pattern="yyyy/MM/dd"/>
					</td>
					<td>${emp.quitDate}</td>
				</tr>
			</c:forEach>
		</c:if>
	</table>
</div>

</body>
</html>

검색 하지 않을 때

 

검색할 때

EL 내장객체인 param (사용자 입력값을 저장한 map)을 이용하여 검색창에 사용자 입력값이 그대로 남아있도록 처리해주었습니다.