Spring Data JPA 페이징과 정렬
Repository 인터페이스 작성 시 JpaRepository가 아니라 PagingAndSortingRepository를 상속하게 하면, Spring Data JPA에서 제공하는 페이징, 정렬 기능을 이용할 수 있다.
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
...
}
PagingAndSortingRepository를 상속하면 findAll(Pageable pageable)이나 findAll(Sort sort)과 같이 Pageable과 Sort 클래스를 파라미터로 받는 메서드를 명세할 수 있다.
기본적으로 제공되는 findAll(Pageable pageable)은 Page 객체를 리턴하지만, 커스텀 메서드를 통해 리턴 타입을 List, Slice 객체로 받을 수 있다.
Page 객체는 전체 페이지의 개수를 알 수 있지만 이를 위해 추가적인 쿼리가 발생한다. List나 Slice 객체로 리턴 타입을 변경하면 전체 페이지의 개수는 모르지만 추가적인 쿼리를 막을 수 있다.
Slice 객체의 경우 다음 페이지가 있는지 여부만을 알 수 있다.
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
Page<User> findAll(Pageable pageable);
List<User> findAll(Pageable pageable);
Slice<User> findAll(Pageable pageable);
}
Pageable 객체는 PageRequest.of() 메서드로 생성이 가능하며, PageRequest.of() 메서드는 page(조회하고자 하는 페이지 번호), size(페이지 당 로우 개수)를 파라미터로 받는다.
페이지는 0부터 시작한다.
오버로딩을 통해 sort(정렬 기준 컬럼 정보, Sort 객체) 파라미터도 함께 사용할 수 있는데, 이 경우 페이징과 정렬이 동시에 처리된다.
Pageable pageable = PageRequest.of(0, 12, Sort.by("id").accending());
페이징 없이 정렬만 하려는 경우 위에 언급한 findAll(Sort sort) 메서드와 같이 Sort 객체만 파라미터로하는 메서드를 작성하면 된다.
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
...
List<User> findAll(Sort sort);
}
Sort 클래스의 and() 메서드를 통해 여러 컬럼을 정렬 기준으로 삼을 수 있다.
Sort idSort = Sort.by("id");
Sort nameSort = Sort.by("name"):
Sort idNameSort = idSort.and(nameSort);
userRepository.findAll(idNameSort);
Sort 객체를 생성할 때 사용하는 컬럼명은 실제 테이블의 컬럼명이 아니라 Entity의 속성 이름으로 지정해야 한다.
// 테이블 컬럼명: post_code / Enitity 속성명: postCode
Sort idSort = Sort.by("postCode");
출처:
https://howtodoinjava.com/spring-boot2/pagination-sorting-example/