인생 디벨로퍼

myBatis 검색 연습, 검색 쿼리 (.feat 페이징) 본문

JAVA Spring

myBatis 검색 연습, 검색 쿼리 (.feat 페이징)

뫄뫙뫄 2023. 6. 23. 01:03
728x90

2023.06.20 - [JAVA Spring] - 페이징 연습

페이징 코드에 추가되는 부분이 많아, 함께 체크!

 

쿼리 만들기

1. like 절 사용

SELECT * FROM [테이블명] WHERE LIKE [조건]

부분적으로 일치하는 칼럼을 찾을때 사용

select * from BOARD_TB where title like '%검색%' or content like '%검색%'

2. 재사용을 위해 include 절 사용

<sql id=""> : 반복 쿼리 선언

 <include refId=""> : sql 문 사용

기존 list 퀴리에 include 를 사용해 sql 쿼리를 적용,

 <sql id="criteria">
            <choose>
                <when test="search!=null">
                    where (title like '%'||#{search}||'%' or content like '%'||#{search}||'%')
                </when>
            </choose>
    </sql>

    <select id="findAllWithPaging" resultType="shop.mtcoding.newblog.dto.board.BoardResp$BoardListRespDto">
         SELECT * FROM (
            SELECT ROWNUM RN, A.* FROM (
                select bt.id, bt.title, bt.content, bt.thumbnail, bt.user_id, ut.username
                        from board_tb bt
                        inner join user_tb ut
                        on bt.user_id = ut.id
                        <include refid="criteria"></include>
                ORDER BY id DESC ) A
            ) WHERE RN BETWEEN #{vo.start} AND #{vo.end}
    </select>

3. 페이징 코드에 include 절 사용

list 코드에만 사용할 경우, 끝 페이지가 옳바르게 나오지 않는다

페이지는 존재하지만, 페이지 않에 결과 게시글이 존재 하지 않게됨.

따라서 꼭 잊지 않고, 게시글 count 쿼리에서 inclde 를 사용해 like 조건절을 적용한다

<select id="countBoard" resultType="int">
        SELECT COUNT(*) FROM BOARD_TB 
        <include refid="criteria"></include>
    </select>

검색 조건에 맞춰, 페이지가 5번까지만 나온다!

 


Controller

    @GetMapping({ "/", "board" })
    public String main(Model model, BoardListRespDto boardListRespDto,
            @RequestParam(value = "search", required = false) String search,
            @RequestParam(defaultValue = "1", value = "nowPage", required = false) String nowPage,
            @RequestParam(value = "cntPerPage", required = false) String cntPerPage) {

        model.addAttribute("dtos", boardRepository.findAllWithUser());

        int total = boardRepository.countBoard(search);
        if (nowPage == null && cntPerPage == null) {
            nowPage = "1";
            cntPerPage = "8";
        } else if (nowPage == null) {
            nowPage = "1";
        } else if (cntPerPage == null) {
            cntPerPage = "8";
        }
        PagingVO vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage));
        // Integer.parseInt(nowPage) 문자열 정수 변환
        model.addAttribute("paging", vo);

        List<BoardListRespDto> boardList = boardRepository.findAllWithPaging(vo, search);
        model.addAttribute("boardList", boardList);

        model.addAttribute("search", search);
        return "board/main";
    }

 

뷰에서 search 값을 받와, 파라미터로 바인딩.

검색 후 페이지를 넘겨 reloding 되도 'search' 를 받아오도록 model 에 담아줌


Repository


.jsp

<form  id="search" action="/board" method="get" class="d-flex m-2" role="search">
    <input name="search" class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
    <button class="btn btn-outline-success" type="submit">Search</button>
 </form>

검색창 뷰 만들기, 

<c:forEach begin="${paging.startPage }" end="${paging.endPage }" var="p">
                        <c:choose>
                            <c:when test="${p == paging.nowPage }">
                                <li class="page-item"><b class="page-link">${p }</b></li>
                            </c:when>
                            <c:when test="${p != paging.nowPage }">
                                <li class="page-item"><a class="page-link" href="/board?search=${search}&nowPage=${p }&cntPerPage=${paging.cntPerPage}">${p }</a></li>
                            </c:when>
                        </c:choose>
                    </c:forEach>

                    <c:if test="${paging.endPage != paging.lastPage}">
                        <li class="page-item">
                            <a class="page-link" href="/board?search=${search}&nowPage=${paging.endPage+1 }&cntPerPage=${paging.cntPerPage}">Next</a>
                        </li>
                    </c:if>

페이징 코드도 수정!

728x90

'JAVA Spring' 카테고리의 다른 글

[Google API] 구글 캘린더 프로젝트 생성, api 키 생성  (0) 2024.10.30
Spring security + my batis  (0) 2024.03.11
myBatis 페이징 연습  (0) 2023.06.20
Cookie 아이디 저장하기  (0) 2023.06.18
[Ajax] 비밀번호 확인  (0) 2023.06.18