[Spring] JpaRepository

Jiwoo·2024년 6월 28일
0

Spring

목록 보기
18/19

📌 JpaRepository

  • JpaRepository<Entity,ID> 붙이면 알맞은 프로그래밍 된 SimpleRepository 구현체 빈이 등록
  • SpringData Common 의 CRUDRepository + PagingAndSortingRepository 쿼리 기능 제공
  • @NotRepositoryBean 된 상위 인터페이스들의 기능을 포함한 구현체가 프로그래밍된다(@NotRepositoryBean = 빈 생성 막음)
  • SpringDataJpa 에 의해 엔티티의 CRUD, 페이징, 정렬 기능 메소드들을 가진 빈 등록 (상위 인터페이스들의 기능)
public interface UserRepository extends JpaRepository<User, Long> {
  
}

📌 Pageable

  • Pageable 인터페이스를 구현한 PageRequest 객체를 만들거나 얻는다
  • PageRequest 객체는 요청된 페이지 숫자와 페이지 사이즈 넘김으로서 만든다
// 첫 페이지 (페이지 사이즈 = 2)
Pageable firstPageWithTwoElements = PageRequest.of(0, 2);
// 두번째 페이지 (페이지 사이즈 = 5)
Pageable secondPageWithFiveElements = PageRequest.of(1, 5);
// 페이지 사용
List<Product> allTenDollarProducts =
productRepository.findAllByPrice(10, secondPageWithFiveElements);
  • findAll(Pageable pageable) 메서드는 Page 객체 리턴

📌 Sorting

  • 쿼리 정렬하기 위해 Sort 객체를 메서드에 전달
  • 정렬과 페이지네이션 둘 다 하고 싶다면? -> 정렬에 대한 디테일 정보를 PageRequest 객체에 전달
Pageable sortedByName = PageRequest.of(0, 3, Sort.by("name"));

Pageable sortedByPriceDesc = PageRequest.of(0, 3, Sort.by("price").descending());

Pageable sortedByPriceDescNameAsc = PageRequest.of(0, 5, Sort.by("price").descending().and(Sort.by("name")));
  • 페이징 없이 정렬만 하는 경우 findAll 메서드와 같이 Sort 객체만 파라미터로 하는 메서드 작성
Page<Product> allProductsSortedByName = productRepository.findAll(Sort.by("name").accending());

0개의 댓글