JPA의 Pageable 인터페이스와 쿼리 메서드로 아주 간단하게 구현했다.
package com.example.backend.repository;
import com.example.backend.entity.board.Board;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BoardRepository extends JpaRepository<Board, Long> {
Page<Board> findAll(Pageable pageable);
}
findAll() 메서드는 PagingAndSortingRepository라는 인터페이스에 있어서 불러다 쓰면 됨.
페이지네이션을 사용할 때 쿼리 메소드에 파라미터에 PageRequest 객체를 넘겨주면 된다.
먼저 컨트롤러 단을 구현해보자.
@GetMapping("/all-boards-with-page/{pageIndex}")
public List<BoardResponse> getAllBoardsWithPage(@PathVariable("pageIndex") int pageIndex) {
return service.getAllBoardListWithPage(pageIndex);
}
클라이언트에게 pageIndex를 받아서 service 메소드한테 넘겨준다.
@Override
public List<BoardResponse> getAllBoardListWithPage(int pageIndex) {
final int PAGE_SIZE = 5;
Sort newest = Sort.by(Sort.Direction.DESC, "boardNo");
PageRequest pageRequest = PageRequest.of(pageIndex, PAGE_SIZE, newest);
Page<Board> boardPage = boardRepository.findAll(pageRequest);
System.out.println(boardPage.toString());
List<Board> entities = boardPage.getContent();
return entities.stream()
.map(BoardResponse::new)
.collect(Collectors.toList());
}
pageIndex: page의 index로, 0부터 시작한다.
pageSize: 한 페이지의 사이즈이다.
Board를 최신순으로 불러오기 위해 Sort 객체를 넘겨줬다.
또한 DTO 객체 리스트로 응답하기 위해 page 객체에서 entity 리스트를 뽑아 BoardResponse로 변환해줬다.
잘 동작하는 것을 확인했고, 클라이언트 api는 다음 시간에,,
🔽 참고한 것
chat gpt
'개발 공부' 카테고리의 다른 글
[Dart] futures, async, await을 활용한 비동기 코드 작성하기 (1) | 2023.07.13 |
---|---|
[Java] 얕은 복사(Shallow Copy)와 깊은 복사(Deep Copy) (0) | 2023.07.06 |
[Flutter] enhanced enum 활용해보기(향상된 enum) (0) | 2023.06.06 |
[Flutter] setState() or markNeedsBuild() called when widget tree was locked. (0) | 2023.05.31 |
Flutter MeterialApp theme 속성으로 ButtonTheme 설정하기 (0) | 2023.05.24 |