본문 바로가기

Spring Boot/Spring Boot

55 : JPA+Pageable 페이징처리 (Springboot + JPA)

 

26- 게시판 만들기4 (페이징 처리)

추가한 기능 페이징처리와, EndUser에게 입력받은 '숫자'에 맞추어 글을 출력 동작순서 1. BoardList.jsp에서 EndUser에게 입력받아 Controller를 통해 BoardLIstCmd로 값을 넘겨준다 (action) 2. BoardListCmd에..

dwc04112.tistory.com

우선 JSP에서 MVC패턴으로 구현한 페이징처리를 보면 너무 복잡하다.

Spring Boot JPA 에서 페이징 처리를 하려면 어떻게 해야할까?

지난시간 까지 만들었던 SpringbootApi에서 구현했다.

 

 


저번에 만든 BoardRepository를 수정하여 JpaRepository를 상속받게 BoardRepository를 생성하자

사진출처 : https://wonit.tistory.com/483

위 다이어그램에서와 같이 생성한 BoardRepository는 JpaRepository를 상속받았고,

또 JpaRepository는 PagingAndSortingRepository를 상속받았다.

여기서 JpaRepository 의 부모 인터페이스인 PagingAndSortingRepository 에서

페이징소팅이라는 기능을 제공한다.

 

 

BoardJpaController

@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping(value = "/boardjpa")
public class BoardJpaController {

    public final BoardJpaService boardJpaService;

    @GetMapping(value = "/")
    public ApiResponse<BoardDTO> getBoardList(@RequestParam int page, @RequestParam int size){
        Page<Board> list = boardJpaService.getBoardList(page, size);
        return new ApiResponse(true, list);
    }

BoardList 출력부분에 페이징처리를 해보자.

url에서 받는 page와 size는 다음과 같은 의미를 가진다.

  • page : page 번호 (몇 페이지인지?)
  • size : page당 보여줄 content 갯수

Page<T> 타입이란?

  • Page 는 일반적인 게시판 형태의 페이징에서 사용된다.
  • Page<T> 타입을 반환 타입으로 받게 된다면 offset과 totalPage 를 이용하여 서비스를 제공할 수 있게된다.
  • Page<T> 타입은 count 쿼리를 포함하는 페이징으로 카운트 쿼리가 자동으로 생성되어 함께 나간다.

 

url에서 받은 page와 size를 Page<T>타입인 list에 넣어 Service로 보낸다.

 


BoardJpaService

    public Page<Board> getBoardList(int page, int size) {
        PageRequest pageRequest = PageRequest.of(page, size);
        return boardRepository.findBoardsByIsDel("N", pageRequest);
    }

PageRequest 객체는 Pageable 인터페이스를 상속받는다.

쉽게 Paging 을 위한 정보를 넘길 수 있는데, 이 정보에는 정렬 정보, 페이지 offset, page와 같은 정보가 담겨있다.

fintBoardsByIsDel에 추가로 PageRequest객체를 함께 넣어 보낸 값을 리턴한다.

 

BoardRepository

@Repository
public interface BoardRepository extends JpaRepository<Board, Integer> {
    List<Board> findAll();
    Page<Board> findBoardsByIsDel(String isDel, Pageable pageable);
    Optional<Board> findBoardById(int id);
}

 

 


Postman에서 출력

page와 size를 설정 후 실행해보자. size를 설정 후 실행하면 자동으로 아래와 같이 페이징 정보가 나온다

 

 

{
    "success": true,
    "message": null,
    "data": {
        "content": [
            {
                "id": 1,
                "author": "aaaa1025aaaa",
                "subject": "wwwww",
                "content": "jjjjjj",
                "writeDate": "2021-10-25",
                "writeTime": "18:05:09",
                "readCount": 0,
                "commentCount": 0,
                "password": "1111",
                "replyRootId": 0,
                "depth": 0,
                "orderNum": 0,
                "isDel": "N"
            },
            {
                "id": 4,
                "author": "xcb1025",
                "subject": "xcbxfsdg",
                "content": "wafaefaef",
                "writeDate": "2021-10-25",
                "writeTime": "18:04:22",
                "readCount": 0,
                "commentCount": 0,
                "password": "0000",
                "replyRootId": 0,
                "depth": 0,
                "orderNum": 0,
                "isDel": "N"
            }
        ],
        "pageable": {
            "sort": {
                "empty": true,
                "sorted": false,
                "unsorted": true
            },
            "offset": 0,
            "pageSize": 2,
            "pageNumber": 0,
            "paged": true,
            "unpaged": false
        },
        "totalPages": 2, // 전체 페이지 갯수 총 3건 데이터 중 2개의 요청이므로 2개 페이지 존재
        "totalElements": 3,
        "last": false, // 마지막 페이지 여부 
        "number": 0,
        "size": 2,  // 페이지 당 출력 갯수  
        "sort": {
            "empty": true,
            "sorted": false,
            "unsorted": true
        },
        "numberOfElements": 2,  // 요청 페이지에서 조회 된 데이터의 갯수
        "first": true,  // 첫 페이지 여부
        "empty": false
    }
}

 

 

출처

https://wonit.tistory.com/483

http://devstory.ibksplatform.com/2020/03/spring-boot-jpa-pageable.html