pageable를 이용한 페이지네이션

이태규·2022년 3월 12일
0

spring

목록 보기
8/64

DB및 DBIMPL (설계부분)

물품목록(페이지정보 1, 2, 3 , 내림차순)

    @Override
    public List<Item> selectlist(Pageable pageable) {
        try {
            Query query = new Query();
            query.with(pageable); // skip().limit()

            query.fields().exclude("filedata", 
            "filetype", "filesize", "filename");

            // 컨트롤러에서 할 수 있음
            Sort sort = Sort.by(Direction.DESC, "_id");
            // Sort , Direction static임
            // DESC는 내림차순 ASC 오름차순
            // 뒤에껀 DB컬렉션 명

            query.with(sort); // sort

            return mongodb.find(query, Item.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

import해야 하는 Query
org.springframework.data.mongodb.core.query.Query
기준, 프로젝션, 정렬 및 쿼리 힌트를 나타내는 MongoDB 쿼리 개체입니다.

with(Sort sort)
Adds a Sort to the Query instance.

Query 참고

물품전체개수 구하기(페이지네이션의 페이지 표시용)

    @Override
    public long selectcount() {
        try {
            Query query = new Query();
            return mongodb.count(query, Item.class);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

컨트롤러

@GetMapping(value = { "/selectlist" })
    public String selectGET(Model model,
            @RequestParam(name = "page", defaultValue = "0") int page) {

        System.out.println("----------------------------");
        System.out.println("다시시작");
        if (page == 0) { // ?page=1을 추가하는 부분
            return "redirect:/item/selectlist?page=1";
        }

        // 페이지네이션 계산
        // 1페이지 => 0 2페이지 => 1

        Pageable pageable = PageRequest.of(page - 1, 10);
        // 페이지를 계산하는 부분
        // 지금은 20개 있어도 10개만 나옴

        List<Item> list = itemDB.selectlist(pageable);

        long pages = itemDB.selectcount();

        // 목록 전송
        model.addAttribute("list", list);
        model.addAttribute("pages", (pages - 1) / 10 + 1);

        return "item/select";
    }

페이지를 param으로 받고, defaultvalue를 0으로 줘서, param없이 /selectlist로 가더라도 &page=0으로 만들어지도록 유도한다. 그리고, 페이지가 0으로 올 경우 다시 page=1로 이동하도록 만든다.

10개의 목록씩 한 페이지를 구성하려고 한다면
Pageable pageable = PageRequest.of(page - 1, 10);
n번부터 10개를 가져간다는 뜻.
0,10이면 0~10
1,10이면 11~20
그리고 전체 개수를 알아야 몇 페이지를 구성할 수 있는지 알 수 있기 때문에
설계부분에 만들어뒀던 전체개수를 구하는 메소드를 사용한다

jsp

<tr th:each="tmp, idx :${list}">
            <td th:text="${idx.count}"></td>
            <td th:text="${tmp.code}"></td>
            <td th:text="${tmp.name}"></td>
            <td th:text="${tmp.price}"></td>
            <td th:text="${tmp.quantity}"></td>
            <td th:text="${tmp.regdate}"></td>
            

            <td>
                <a th:href="@{/item/update(code=${tmp.code})}">수정</a>
                <a th:href="@{/item/delete2(code=${tmp.code})}">삭제</a>
            </td>
        </tr>
    </table>

    <th:block th:each="i : ${#numbers.sequence(1,pages)}">
        <a th:href="@{/item/selectlist(page=${i})}" th:text="${i}"></a>
    </th:block>

i : ${#numbers.sequence(1,pages)}는 1페이지부터 pages까지 반복한다는 의미이다.

참고: https://tecoble.techcourse.co.kr/post/2021-08-15-pageable/텍스트

profile
한 걸음씩 나아가자

0개의 댓글