사용자들의 리뷰를 10개씩 조회하는 페이징 기법을 구현해 봅시다 ~
[ JPA 로 Pagination 구현하기 ]
0. Pagination 이란?
- 데이터 조회 시, 페이지를 나누어 정해진 개수만큼의 데이터만 가져오기
🏠 https://www.techtarget.com/whatis/definition/pagination
What is pagination? – TechTarget Definition
Learn about pagination -- the process of separating print or digital content into pages -- and explore its use cases, benefits and best practices.
www.techtarget.com
1. Controller
@RestController
@RequestMapping("/post")
@RequiredArgsConstructor
public class ReviewController {
private final ReviewService reviewService;
// 게시글 리뷰 조회 (0번 페이지부터 10개씩 최신순으로 조회)
@GetMapping("/{postId}/review")
public ApiResponse<List<ReviewResponseDTO.getReviewResponseDTO>> getPostReview(@PathVariable("postId") Long postId,
@RequestParam(value="page", defaultValue="0") int page) {
Page<Review> reviewList = reviewService.getPostReview(postId, page);
return ApiResponse.onSuccess(ReviewConverter.getReviewResult(reviewList));
}
}
· 조회할 게시글의 id 입력받기
· 조회할 리뷰의 페이지 번호 입력받기 (페이지 시작 번호는 defaultValue 로 설정 가능)
2. Service
@Service
@RequiredArgsConstructor
@Transactional
public class ReviewServiceImpl implements ReviewService {
private final PostRepository postRepository;
private final ReviewRepository reviewRepository;
// 게시글 리뷰 조회
public Page<Review> getPostReview(Long postId, int page) {
// 게시글 조회
Post post = postRepository.findById(postId).orElseThrow(() -> new GeneralException(ErrorStatus.POST_NOT_FOUND));
// 게시글 id 를 가진 리뷰 조회 (+ 페이지네이션)
List<Sort.Order> sorts = new ArrayList<>();
sorts.add(Sort.Order.desc("createdAt"));
Pageable pageable = PageRequest.of(page, 10, Sort.by(sorts));
return reviewRepository.findAllByPost(post, pageable);
}
}
· 최신 순으로 조회 : Sort.Order.desc("createdAt")
· PageRequest.of( 조회할 페이지 번호, 페이지 크기, 정렬 방법 )
3. Repository
public interface ReviewRepository extends JpaRepository<Review, Long> {
// 게시글 리뷰 조회 (0번 페이지부터 10개씩 최신순으로 조회)
Page<Review> findAllByPost(Post past, Pageable pageable);
}
'Spring > [P] AI 챗봇 기반 맞춤형 레시피 서비스' 카테고리의 다른 글
[SpringBoot/Querydsl] QnA 대댓글 (2) 작성 (2) | 2024.03.04 |
---|---|
[SpringBoot/Querydsl] QnA 대댓글 (1) Querydsl 프로젝트 설정 (0) | 2024.03.01 |
[SpringBoot/ChatGPT] ChatGPT API (5) DB 기반 질문 요청 (2) | 2024.02.28 |
[SpringBoot/ChatGPT] ChatGPT API (4) 일반 대화 - 메세지 반환 (0) | 2024.02.27 |
[SpringBoot/ChatGPT] ChatGPT API (3) 일반 대화 - 메세지 전송 (0) | 2024.02.26 |