BACK/SPRING

Spring Boot Project(5) - 게시글 페이징, 필터링하기

연듀 2023. 1. 24. 21:23

 

Pageable을 이용하면 간단하게 Pagination 와 Sorting을 처리할 수 있다.

 

 

PostsRepository

public interface PostsRepository extends JpaRepository<Posts, Long> {

    Page<Posts> findAll(Pageable pageable);
    
    @Query(value="select p from Posts p where p.subject = :subject and p.division = :division and p.is_progress = :is_progress")
    Page<Posts> findAllByFiltering(Pageable pageable, @Param("subject") String subject, @Param("division") String division, @Param("is_progress") int is_progress);

}

 

Pageable

PostsRepository는 JpaRepository를 상속받았고, JpaRepository는 PagingAndSortingRepository라는 클래스를 상속받는다.

이로 인해 PostsRepository는 Pageable을 매개변수로 Pagination과 Sorting을 할 수 있다. 

findAll 함수에 pageable을 매개변수로 받는다.

 

@Query

SQL과 유사한 JPQL (Java Persistence Query Language) 라는 객체지향 쿼리 언어를 통해 복잡한 쿼리 처리를 지원한다.

  • JPQL - 테이블이 아닌 엔티티 객체를 대상으로 검색하는 객체지향 쿼리, SQL 추상화로 인해 특정 db sql 에 의존하지 않음

 

findAllByFiltering 함수에서는 @Param을 통해 매개변수로 넘어온 값을  JPQL에 들어갈 변수로 지정해 필터링된 게시글들을 조회한다. 

 

 

PostsApiController

    @ApiOperation(value="게시글 전체 조회")
    @GetMapping("/postList")
    public Page<PostListDto> findAllList(@PageableDefault(size=6) Pageable pageable){
        return postsService.pageList(pageable).map(PostListDto::new); // = map(posts -> new PostListDto(posts));
    }
    
    @ApiOperation(value="게시글 목록 필터링 조회", notes = "과목, 분반, 진행여부에 따라 조회")
    @GetMapping("/postList/filtering")
    public Page<PostListDto> findFilteringList(@PageableDefault(size=6, sort = "id", direction = Sort.Direction.DESC) Pageable pageable, @RequestParam String subject, @RequestParam String division, @RequestParam int is_progress){
        return postsService.findFilteringList(pageable, subject, division, is_progress).map(PostListDto::new);
    }

 

  • page : 요청할 페이지 번호
  • size : 한 페이지 당 조회 할 갯수 (default : 10)
  • sort : 정렬의 기준이 되는 속성 정의
  • direction: 오름차순과 내림차순 중 기준 선택 
  • Pageable pageable: PageableDefault 값을 갖고 있는 변수를 선언 

 

@RequestParam: url 뒤에 붙는 파라미터의 값을 가져올 때 사용한다. 

 

 

 

PostsService

    @Transactional(readOnly = true)
    public Page<Posts> pageList(Pageable pageable){
        return postsRepository.findAll(pageable);
    }
    @Transactional
    public Page<Posts> findFilteringList(Pageable pageable, String subject, String division, int is_progress){
        return postsRepository.findAllByFiltering(pageable, subject, division, is_progress);
    }