본문 바로가기

스프링부트 관련(spring boot, mybatis)

Mybatis에서 Pageable 사용하기

Mybatis를 사용하면서 Pageable을 사용할수는 없을지 알아보았다. 나도 찾아보기 전까지는 JPA에서만 사용할 수 있을줄 알았는데 그게 아니였다. Mybatis에서 Pageable을 사용하는 과정을 정리해 보았다.

 

    implementation 'org.springframework.data:spring-data-commons'

JPA를 implementation 하지 않고 위 data commons를 이용하면 Pageable을 사용할 수 있다.

 

게시글 목록 조회에 Pageable을 적용해 보았다.

 

Service

public Page<ResponseDto> getBoards(Pageable pageable) {
    ...

    Page<ResponseDto> page = new PageImpl<>(ResponseDtoList, pageable, count);
    return page;
}

PageImpl은 구현체이다. 여기에 페이지네이션할 객체의 리스트를 넣고, pageable 객체, 그리고 총 개수를 매개변수로 넣어주면 page 객체를 생성할 수 있다.

 

controller

@GetMapping()
public ResponseEntity<Page<ResponseDto>> getBoards(Pageable pageable) {
    Page<ResponseDto> responseDtoPage = this.boardService.getBoards(pageable);
    return ResponseEntity.status(HttpStatus.OK).body(ResponseDtoPage);
}

Page를 그대로 응답으로 보낼 수 있다.

 

응답은 요런식으로 온다.

content에 list의 값들이 담기게 된다.

 

thymeleaf를 사용한다면, content로 값을 불러올 수도 있지만, 반복문을 사용한다면 content를 사용하지 않고 page값 자체를 반복문 돌려도 안의 내용을 꺼내올 수있다.

 

page는 기본적으로 0부터 시작한다. 

 

 

참고

 

https://velog.io/@dani0817/Spring-Boot-%ED%8E%98%EC%9D%B4%EC%A7%95Paging-%EC%A0%81%EC%9A%A9