728x90
반응형
##페이징 구현
: 스프링부트에서 제공하는 Sort, Pageable, Page 객체 이용
1.ProductController
: 페이지 정보 ,페이지당 객체 갯수, 정렬기준 , 정렬방향 정보로 검색해서 반환
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@GetMapping("/api/products")
public Page<Product> getProducts(
// 현재 페이지 번호, 페이지당 객체갯수, 정렬기중, 정렬방향
@RequestParam("page") int page,
@RequestParam("size") int size,
@RequestParam("sortBy") String sortBy,
@RequestParam("isAsc") boolean isAsc,
@AuthenticationPrincipal UserDetailsImpl userDetails
) {
Long userId = userDetails.getUser().getId();
page = page - 1;
return productService.getProducts(userId, page , size, sortBy, isAsc);
}
|
cs |
2.ProductService
: Sort 객체에 정렬기중, 방향 정보 저장하고 , pageable 객체에 페이지번호,사이즈,sort정보 저장해서 리파지토리에 pageable 객체로 정보를 넘겨서 검색
1
2
3
4
5
6
7
8
9
10
|
public Page<Product> getProducts(Long userId,int page,int size,String sortBy,boolean isAsc){
// 페이지, 페이지당 객체 갯수, 정렬기준,정렬방향 정보를 담은 스프링 내장 pageable 객체 생성
// 스프링에서 고정적으로 쓰이는 것. 갖다 쓰면 됨.
Sort.Direction direction = isAsc ? Sort.Direction.ASC : Sort.Direction.DESC;
Sort sort = Sort.by(direction, sortBy);
Pageable pageable = PageRequest.of(page, size, sort);
return productRepository.findAllByUserId(userId, pageable);
}
|
cs |
3.ProductRepository
: Pageable 객체를 담는 jpa 인터페이스만 선언해주면 됨
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.sparta_spring.sparta_springcore_week01.repository;
import com.sparta_spring.sparta_springcore_week01.model.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ProductRepository extends JpaRepository<Product,Long> {
// List<Product> findAllByUserId(Long userId);
Page<Product> findAllByUserId(Long userId, Pageable pageable); // 페이빙 정보를 넘겨줘서 jpa 활용
}
|
cs |
반응형
'SpringBoot > 스파르타 스프링 심화' 카테고리의 다른 글
[스파르타 스프링 심화] 04.05 영속성 컨텍스트 이해 (0) | 2021.08.31 |
---|---|
[스파르타 스프링 심화] 04.02 Spring Data JPA 이해 (0) | 2021.08.24 |
[스파르타 스프링 심화] 03.08 통합 테스트란? (0) | 2021.08.23 |
[스파르타 스프링 심화] 03.05 Edge 케이스를 고려한 단위 테스트 (2) (0) | 2021.08.22 |
[스파르타 스프링 심화] 03.04 Edge 케이스를 고려한 단위 테스트 (1) (0) | 2021.08.22 |