๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’Ž/Spring

[Spring] Pageable ๋‹ค์ค‘ Sorting | PageableDefault | Pagination

by dar0m! 2020. 1. 9.

SQL์„ Pageable์„ ์ด์šฉํ•˜์—ฌ ๋‚˜ํƒ€๋‚ด๊ธฐ

select * from luvket.luvkets order by status desc, created_at desc limit 0, 25;

์œ„์™€ ๊ฐ™์€ SQL๋ฌธ์„ Spring ์—์„œ Pageable์„ ์ด์šฉํ•˜์—ฌ ํ‘œํ˜„ํ•œ๋‹ค๋ฉด ์ด๋ ‡๊ฒŒ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

1
2
3
4
5
6
7
8
9
    @GetMapping("")
    public LuvketResponse<List<LuvketDto>> search(@PageableDefault(size = 25)
                                                  @SortDefault.SortDefaults({
                                                      @SortDefault(sort = "status", direction = Sort.Direction.DESC),
                                                      @SortDefault(sort = "createdAt", direction = Sort.Direction.DESC)
                                                  })
                                                      Pageable pageable){
        return luvketService.search(pageable);
    }
cs

 

PageableDefault

PageableDefault ์€ ์•„๋ž˜ ๋ฌธ์žฅ์ฒ˜๋Ÿผ

1
@PageableDefault(sort = "id", direction = Sort.Direction.DESC, size = 25) Pageable pageable
cs
  1. page
  2. size
  3. sort

๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ์ด ๋ฐฉ๋ฒ•์—์„œ๋Š” Sort๋กœ ํ•œ ๊ฐ€์ง€ ์กฐ๊ฑด๋ฐ–์— ์ ์šฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.

 

SortDefault

๊ทธ๋ž˜์„œ @PageableDefault ์—์„œ๋Š” page ์™€ size๋งŒ ์„ค์ •ํ•ด๋‘๊ณ ,

@SortDefault ๋ฅผ ์ด์šฉํ•˜์—ฌ ์—ฌ๋Ÿฌ ์ •๋ ฌ์กฐ๊ฑด์„ ์ถ”๊ฐ€ํ•˜๋ฉด ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

1
2
3
4
    @SortDefault.SortDefaults({                                     
        @SortDefault(sort = "status", direction = Sort.Direction.DESC),
        @SortDefault(sort = "createdAt", direction = Sort.Direction.DESC)
    })
cs

 

 

๋‹ค๋ฅธ ๋ฐฉ๋ฒ•: PageRequest

์ •๋ ฌ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ PageRequest ๊ฐ์ฒด์— ์ „๋‹ฌํ•˜์—ฌ Pageable ์„ ์ƒ์„ฑํ•˜๊ณ  repository.findALL( ) ๊ด„ํ˜ธ ์•ˆ์— ํ•ด๋‹น Pageable์„ ๋„ฃ์–ด์ฃผ๋ฉด ํŽ˜์ด์ง€๋„ค์ด์…˜๊ณผ ์ •๋ ฌ ๋‘˜ ๋‹ค ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

1
2
3
Page<Product> allProductsSortedByName = productRepository.findAll(Sort.by("name"));
 
Pageable sortedByPriceDescNameAsc = PageRequest.of(05, Sort.by("price").descending().and(Sort.by("name")));
cs

 

'๐Ÿ’Ž > Spring' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[JPA] ์ฆ‰์‹œ ๋กœ๋”ฉ, ์ง€์—ฐ ๋กœ๋”ฉ | FetchType.EAGER, FetchType.LAZY  (0) 2021.08.31
[Spring] DI(Dependency Injection)  (0) 2021.05.02
[Spring] PSA (Portable Service Abstraction)  (0) 2021.05.02
[Spring] AOP  (0) 2021.04.18

๋Œ“๊ธ€