본문 바로가기

[CRUD] 검색

2023. 11. 28.
반응형
검색 > 페이징 > Ajax > 파일 업/다운로드

 

1. Mapper 작성

<!-- 이전 코드 -->
    <sql id='searchWhere'>
        <where>
            <choose>
                <when test='searchType == "choise" '>
                	1=1
                </when>
                <when test='searchType == "title" '>
                	title like '%' || #{keyword} || '%'
                </when>
                <when test='searchType == "writer" '>
                	writer like '%' || #{keyword} || '%'
                </when>
                <when test='searchType == "titleAndContent" '>
                	(title like '%' || #{keyword} || '%' or content like '%' || #{keyword} || '%')
                </when> 
            </choose>
            <if test='startDate != null and startDate != "" '>
            	and to_char(reg_date. 'yyyy-MM-dd') between #{startDate} and #{endDate}
            </if>
        </where>
    </sql>

    <select id="showBoardList" resultMap="Board">
        select
            board_seq,
            writer,
            title,
            content,
            reg_date,
            upt_date,
            view_cnt
        from board
        <include refid="searchWhere"></include>
        order by board_seq desc
    </select>

검색할 수 있는 항목은 제목, 작성자, 제목 혹은 글내용, 업로드 날짜 입니다.
중복되는 쿼리를 <sql>과 <include> 문으로 효과적으로 관리하여, 앞으로도 쉽게 변할 수 있는 검색 옵션을 간편하게 관리합니다.
searchType이 choice인 경우는 아무것도 선택하지 않았을 입니다. 이런 경우, 모든 항을 출력하기 있는 1=1를 적용하여 다른 조건(날짜 검색)과도 잘 어우러질 수 있도록 합니다. (ex. 1=1 and 23-09-09 ~ 23-10-10)

2. Dao, DaoImpl 수정

// Dao
	/* 이전 getList
    List<Map<String, Object>> getList();
    */
    List<Map<String, Object>> getList(Map<String, Object> param);
    
// DaoImpl
	/* 이전 getList
    @Override
    public List<Map<String, Object>> getList(){
    	return sqlsession.selectList("BoardMapper.showBoardList");
    }
    */
    @Override
    public List<Map<String, Object>> getList(Map<String, Object> param){
    	return sqlsession.selectList("BoardMapper.showBoardList", param);
    }

이전에는 파라미터 없이 목록만을 출력하는 간단한 형태였지만, 이제는 검색 조건이 추가되었기 때문에 Map 형식의 파라미터를 전달하도록 변경했습니다.

3. Service, ServiceImpl 수정

// Service
	/* 이전 getList
    List<Map<String, Object>> getList();
    */
    List<Map<String, Object>> getList(Map<String, Object> param);
    
// ServiceImpl
	/* 이전 getList
    @Override
    public List<Map<String, Object>> getList(){
    	return boardDao.getList();
    }
    */
    @Override
    public List<Map<String, Object>> getList(Map<String, Object> param){
    	return boardDao.getList(param);
    }

 

 

Dao, DaoImpl과 같은 이유로 파라미터를 전달해주도록 수정합니다.

4. Controller 수정

	/* 이전 Controller
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, @RequestParam Map<String, Object> param) {
        List<Map<String, Object>> boardList = boardSer.getList(param);

        model.addAttribute("boardList", boardList);

        return "listPage";
    }
    */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, @RequestParam Map<String, Object> param) {
        List<Map<String, Object>> boardList = boardSer.getList(param);

        model.addAttribute("boardList", boardList);

        return "listPage";
    }

 

5. listPage.jsp 수정

    <main>
        <div class='container'>
        	<!-- 기존 코드 중간에 삽입 -->
            <form id='searchForm'>
                <label>상세조건</label>
                <select name='searchType'>
                    <option value='choice' ${param.searchType == 'choice' ? 'selected' : ''}>선 택</option>
                    <option value='title' ${param.searchType == 'title' ? 'selected' : ''}>제 목</option>
                    <option value='writer' ${param.searchType == 'writer' ? 'selected' : ''}>글쓴이</option>
                    <option value='titleAndContent' ${param.searchType == 'titleAndContent' ? 'selected' : ''}>제목or내용</option>
                </select>
                <input type='text' id='keyword' name='keyword' value="${param.keyword }">
                <input type="date" id="startDate" name="startDate" value="${param.startDate}">
                <input type="date" id="endDate" name="endDate" value="${param.endDate }">
                <button>검색</button>
            </form>
            <br>
            <!-- 여기까지 -->
            <form id='delForm'>

 

6. 결과물

결과물 : 다양한 검색 환경

 

후기

이번에는 조금 더 심화된 MyBatis 쿼리문과 함께 검색에 대해서 알아봤습니다. 특히 <sql>, <include>문은 실제 프로젝트에서도 많이 사용 될 것이라고 생각했습니다. 
특히, 검색 후에 검색 내용이 남아있도록 ${param.변수명}을 사용했는데 컨트롤러에서 따로 모델에 속성을 추가해주지 않고도 남아있다는 것을 처음 알았습니다. 따로 알아보니 제가 @RequestParam를 사용했고 Spring MVC에서 제공하는 편리한 기능 중 하나라고 하더군요. 정말 유익한 시간이었습니다.

오늘은 에러나 실수는 없었고 기존에 몰랐던 유익한 정보들을 알아가는 시간이었습니다! 다음은 페이징으로 돌아오겠습니다. 빠잇~!
반응형

'Spring > CRUD Project' 카테고리의 다른 글

[CRUD] Ajax : 비동기 통신  (1) 2023.11.30
[CRUD] 페이징  (0) 2023.11.29
[CRUD] Delete : 글 삭제하기  (1) 2023.11.27
[CRUD] Update : 글 수정하기  (1) 2023.11.24
[CRUD] Read : 글 읽기  (1) 2023.11.23
댓글