본문 바로가기

Spring/JPA

5) Spring Data JPA 5부 - QueryDSL Paging , Sort

반응형

QueyDsl 로 Pasing 처리를 하기 위해서는 어떻게 처리를 해야 할까?

간단하게 PageRequest parameter를 이용한 방법을 알아보자 

먼저 Controller 부분이다.

 

@GetMapping("/findQueryDslPasingTest")
    public List<ProductDto> findQueryDslPasingTest(String productName , String itemName , Pageable pageable) throws Exception {
//        PageRequest pageRequest = PageRequest.of(0, 3, Sort.by("productName").descending());

        List<Product> products = userService.findProductByCustom(productName , itemName , pageable);
        List<ProductDto > productDtoList = products.stream().map(ProductDto::of).collect(Collectors.toList());

        return productDtoList;
    }

Request Parameter로 Pageable parameter를 받고 있다. Pageable parameter를 받아서 어떻게 처리를 하는지 알아보자 

아래는 service 부분과 repository 부분이다.

public List<Product> findProductByCustom(String productName , String itemName , Pageable pageable )throws Exception{
        return productRepo.findProductByCustomPasing(productName , itemName , pageable);
    }
 public List<Product> findProductByCustomPasing(String productName , String itemName , Pageable pageable){
        QProduct product = QProduct.product;
        JPAQuery<Product> query = queryFactory.selectFrom(product).leftJoin(product.items).fetchJoin()
                .where(SamplePredicate.productPredicate(productName,  itemName));
                //.limit(pageable.getPageSize()).offset(pageable.getOffset());


        List<Product> products = getQuerydsl().applyPagination(pageable, query).fetch();

        return products;
    }

위 Repository에서 보면 굉장히 단순히 applyPagination 을 하고 있는데 이부분을 사용하지 않고 

queryFactory에서 limit  , offset 과 sort를  각각 구현해도 상관이  없다. 하지만 간단히 applyPagination 만 하게 되면 

Pageable에서 받아온 page , size , sort 값 부분을 자동으로 처리해 주니 굉장히 편리하다. 

 

이제 Pageable Parameter를 어떻게 넘겨 줘야하는지 알아보자.

아래  전체 Product에 대한 조회 결과이다 .

 

총 4개의 Product가 조회된다. 이제 여기에 Pasing해보자  Page size를 3으로 해보면 총 2개의 Page가 될것이고 product Name 으로 descending 하게되면 2번째 Page 의 첫번째 값은 ProductTest1 이 될것이다. 

 

위 요청 parameterf를 보면 page와 size값을 간단히 넘기고 sort에 대한 값도 넘겨 주고 예측한 결과가 정확히 나오는것을 확인 할 수 있다.

 

 

git hub : https://github.com/devraccon/SpringJpaTest