팁
1. 모든 응답을 Page<T>로 받지 말고 List<T>가 필요한 경우 응답은 List<T> .
전체 count 쿼리가 추가로 발생하는 Page<T> 보다는 List<T>가 대용량 처리할 때 더 안정적이고 빠르다.
2. Pageable 과 실제 페이지사이의 -1 문제
JPA 페이지는 0부터인데 화면은 1부터 시작하는 상황
=> PageDTO 를 만들어서 toPageable() 메서드를 사용.
public class PageDTO {
@Positive // 0보다 큰수
private Integer currentPage;
private Integer size;
private String sortBy;
public Pageable toPageable() {
return PageRequest.of(currentPage-1, size, Sort.by(sortBy).descending());
}
}
페이지 반환 타입
1. Page<T> 타입
- 게시판 형태의 페이징에서 사용
- 전체 요소 갯수도 함께 조회 (`totalElements`)
// 응답
{
"content": [
{"id": 1, "username": "User 1", "address": "Korea", "age": 0},
...
{"id": 5, "username": "User 4", "address": "Korea", "age": 4}
],
"pageable": {
"sort": {
"sorted": false, // 정렬 상태
"unsorted": true,
"empty": true
},
"pageSize": 5, // 페이지 크기
"pageNumber": 0, // 페이지 번호 (0번 부터 시작)
"offset": 0, // 해당 페이지의 첫번째 요소의 전체 순번 (다음 페이지에서는 5)
"paged": true,
"unpaged": false
},
"totalPages": 20, // 페이지로 제공되는 총 페이지 수
"totalElements": 100, // 모든 페이지에 존재하는 총 원소 수
"last": false, // 마지막 페이지 여부
"number": 0,
"sort": {
"sorted": false, // 정렬 사용 여부
"unsorted": true,
"empty": true
},
"size": 5, // Contents 사이즈
"numberOfElements": 5, // Contents 의 원소 수
"first": true, // 첫페이지 여부
"empty": false // 공백 여부
}
2. Slice<T> 타입
- 더보기 형태의 페이징에서 사용
- 전체 요소 개수 대신 `offset` 필드로 조회
- 따라서 count 쿼리가 발생되지 않고 limit+1 조회 ( offset 은 성능이 좋지 않다.)
// 응답
{
"content": [
{ "id": 13, "username": "User 12", "address": "Korea", "age": 12 },
...
{ "id": 16, "username": "User 15", "address": "Korea", "age": 15 }
],
"pageable": {
"sort": { "sorted": false, "unsorted": true, "empty": true },
"pageNumber": 3,
"pageSize": 4,
"offset": 12,
"paged": true,
"unpaged": false
},
"number": 3,
"numberOfElements": 4,
"first": false,
"last": false,
"size": 4,
"sort": { "sorted": false, "unsorted": true, "empty": true },
"empty": false
}
3. List<T> 타입
- 전체 목록보기 형태의 페이징에서 사용
- 기본 타입으로 count 조회가 발생하지 않는다
'Spring' 카테고리의 다른 글
| Spring Day 31 : Soft Delete v2 (2) | 2024.03.11 |
|---|---|
| Spring Day 30 : 통합 테스트, 단위 테스트 차이 (0) | 2024.03.08 |
| Spring Day 28 : 영속성 컨텍스트 특징 (0) | 2024.03.06 |
| Spring Day 27 : Repository 기능 제한 (0) | 2024.03.05 |
| Spring Day 26 : 코드 리팩토링 (팔로우 기능) (0) | 2024.03.04 |