Pageable
Row수가 많은 Database에 많은 사용자들이 select를 할 때 많은 양의 row을 한꺼번에 조회하려고 하면 부하가 걸릴 수 있다. 그렇기 때문에 row단위로 페이징 처리하여 조회를 할 수 있도록 해주는 것을 페이징 쿼리 라고 한다.
RestController 에서 어떻게 페이징 처리를 하는 지 알아본다!
나는 @PageableDefault
/ Pageable
을 이용해서 페이징 처리를 해주었다
페이징 쿼리
먼저 LIMIT 조건을 걸어 1~20개의 ROW을 읽어 올 수 있는 쿼리
SELECT * FROM subway.programmer ORDER BY id LIMIT 20, 10;
첫번째 레코드부터 20번째 레코드까지 읽어서 버리고 10개의 레코드를 읽어 반환. 이 쿼리는 ROW가 많을 때 뒷 ROW로 갈 수록 성능이 저하 되기 때문에 PK를 조건절에 걸어준다
SELECT * FROM subway.programmer
WHERE subway.programmer.id >= 20000
ORDER BY id LIMIT 0, 10;
RestApi의 Paging
조회 시에 해당 Api 메서드는 페이징 처리를 한다는 것을 Parameter에 추가를 해준다.
- controller
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; ...
@GetMapping("/favorites")
public ResponseEntity getFavorites(@AuthenticationPrincipal LoginMember loginMember,
@PageableDefault(size = 5, sort = "id", direction = Sort.Direction.DESC) Pageable pageable) {
List favorites = favoriteService.findFavorites(loginMember, pageable);
return ResponseEntity.ok().body(favorites);
}
@PageableDefault
(size = 5, sort = "id", direction = Sort.Direction.DESC) Pageable pageable
- 5개의 row씩 조회할 것이며 "id" 순으로 정렬을 해서 가져올 것.
- service
public List findFavorites(LoginMember loginMember, Pageable pageable) { List favorites = favoriteRepository.findByMemberId(loginMember.getId(), pageable); Map<Long, Station> stations = extractStations(favorites); return favorites.stream() .map(it -> FavoriteResponse.of( it, StationResponse.of(stations.get(it.getSourceStationId())), StationResponse.of(stations.get(it.getTargetStationId())))) .collect(Collectors.toList()); }
- repository
List findByMemberId(Long memberId, Pageable pageable);
마치며
이렇게 페이징 처리를 해서 많은 양의 row을 가져오기보다는 보여주려는 row 수 만큼 페이징처리를 하면 조회 속도를 개선 할 수 있다.
'Programming > Spring' 카테고리의 다른 글
[Springboot] MySQL Replication (0) | 2021.07.11 |
---|---|
[Spring] 롬복(Lombok) (0) | 2021.01.21 |
[Spring] #4. MAVEN 설치 및 Eclipse 연동 (0) | 2021.01.14 |
[Spring] #3. Eclipse SVN 설치 (0) | 2021.01.14 |
[Spring] #2. Spring Tool Suite 설치 및 프로젝트 생성 (0) | 2021.01.14 |