본문 바로가기
프레임워크/스프링

[Spring] TMDB API 영화 데이터 DB 저장 (4)

by Yikanghee 2022. 5. 16.

이번에 해준 것은 paging을 해주었다. 페이지 처리와 한 페이지에

얼마 만큼의 데이터가 들어가는에 대한 코드이다

 

먼저 Controller를 작성해 주었다

@GetMapping("/api/movies")
public Page<Movie> getAllMovies(
        @RequestParam("page") int page, // 요청페이지
        @RequestParam("size") int size, // 요청 사이즈 (게시글에 몇개씩 보여줄지)
        @RequestParam("sort") int sort, 
) {
    Pageable pageable = PageRequest.of(page-1, size);

    Page<Movie> movies = movieRepository.findAllByOrderByCreatedAtDesc(pageable);
    return movies;
}

back에서 JPA를 사용하여 Paging처리를 하면page 정보는 0부터 시작하고

front에서는 1부터 시작하여 오류가 발생한다.

 

그 문제를 해결하기 위해 page-1를 꼭 해주어야 한다.

 

그리고 Repository를 통해서 Entity에 연결해주면 완성이다

 

@Transactional(readOnly = true)
public interface MovieRepository extends JpaRepository<Movie,Long>, QuerydslPredicateExecutor<Movie> {
    Page<Movie> findAllByOrderByCreatedAtDesc(Pageable pageable);
}

 

댓글