스프링 게시판 API 만들기 3

🌎·2023년 5월 15일
0

스프링 공부

목록 보기
5/11

새로운 기능을 추가해보자

데이터를 가져올 때 검색, 정렬, 갯수제한 기능을 추가해 보려고한다.
갯수제한을 그냥 limit로 보는게 아니라 Pagination느낌으로 해보려고 한다.

Spring Data JPA가 제공하는 PageNation이 있는데, Pageable과 PageRequest이다.
Pageable은 페이지네이션 정보를 담기 위한 인터페이스, PageRequest은 구현체이다.

Pageable 인터페이스를 확인해보면,

pageNumber, pageSize, offset과 같은 페이징 구현에 필요한 값들을 편하게 구할 수 있는 메소들을 추상화 시켜놓은 것을 확인할 수 있다.

이제 이것을 이용해서 한 번 구현해보자!

먼저 Repository를 구현해보자.

	List<Board> findByTitleContainingOrderByCreatedAtDesc(String title, Pageable pageable);

위의 구문은 title 단어가 들어 있는 제목을 탐색하고(findByTitleContaining), created_at을 기준으로 내림차순(desc)을 하겠다는(OrderByCreated) 의미이다.

이것을 Service 계층에서 사용해보자.
이전에 만들어 놓았던 findAll() 메소드를 수정해서 사용할 것이다.

    @Override
    public List<Board> findAll(String title, String order, Pageable pageable) {
        if(order.equalsIgnoreCase("DESC")) {
            return repository.findByTitleContainingOrderByCreatedAtDesc(title, pageable);
        } else {
            return repository.findByTitleContainingOrderByCreatedAtAsc(title, pageable);
        }
    }

나는 내림차순, 오름차순을 구분해 주고 싶어서 Repository에 메소드를 하나 더 생성했다.

아무튼, findAll() 메소드가 받는 매개변수도 달라졌기 때문에 Controller 계층도 수정을 해줘야한다.

    @GetMapping()
    public ResponseEntity<List<Board>> findAllBoards(@RequestParam String title, @RequestParam String order, Pageable pageable) {
        List<Board> boards = boardService.findAll(title, order, pageable);
        return ResponseEntity.status(HttpStatus.OK)
                .body(boards);
    }

이제 모든 준비는 끝났다!
포스트맨으로 API를 호출해 보면,

	[GET] http://localhost:8080/boards?page=0&size=5&title=영화&order=asc
[
    {
        "id": 5,
        "title": "어린왕자 만화영화 봤니?",
        "content": "재밌더라~",
        "createdAt": "2023-05-14T15:33:31.000+00:00",
        "updatedAt": "2023-05-14T15:33:31.000+00:00",
        "isDeleted": null
    },
    {
        "id": 6,
        "title": "어린왕자 만화영화 봤니?",
        "content": "재밌더라~",
        "createdAt": "2023-05-14T15:34:26.000+00:00",
        "updatedAt": "2023-05-14T15:34:26.000+00:00",
        "isDeleted": null
    },
    {
        "id": 7,
        "title": "어린왕자 만화영화 봤니?",
        "content": "재밌더라~",
        "createdAt": "2023-05-14T15:34:30.000+00:00",
        "updatedAt": "2023-05-14T15:34:30.000+00:00",
        "isDeleted": null
    },
    {
        "id": 8,
        "title": "어린왕자 만화영화 봤니?",
        "content": "재밌더라~",
        "createdAt": "2023-05-14T15:36:10.000+00:00",
        "updatedAt": "2023-05-14T15:36:10.000+00:00",
        "isDeleted": null
    },
    {
        "id": 9,
        "title": "어린왕자 만화영화 봤니?",
        "content": "재밌더라~",
        "createdAt": "2023-05-14T15:37:51.000+00:00",
        "updatedAt": "2023-05-14T15:37:51.000+00:00",
        "isDeleted": "N"
    }
]

이런 결과가 나오는 것을 확인해 볼 수 있다.
데이터들은 내가 계속 같은 값만 넣어서 똑같은 값을 보여주는 것일 뿐이다...
잘보면 createdAt 시간은 다르다... ㅎㅎ

page를 1로 바꾸면 이 데이터들 다음 데이터부터 5개가 출력된다.

끝 -*

profile
영차영차

0개의 댓글