코딩 나도 할 수 있다!!

2024.06.24 (월) 페이징

혹시나도? 2024. 6. 24. 19:01

과제에서 페이징을 하라는 조건이 있었다

먼저 

@GetMapping
fun getPostList(): ResponseEntity<List<PostResponse>> {
    return ResponseEntity.ok(postService.getPostList())
}

이렇게 전체 포스트를 조회할 수 있는 부분에서 

@GetMapping("/search")
fun getPostPage(
    @PageableDefault(size = 10, sort = ["createdAt"]) pageable: Pageable,
    @RequestParam(value = "title", required = false) title: String
): ResponseEntity<Page<PostResponse>> {
    return ResponseEntity.ok(postService.getPostPage(pageable, title))
}

이렇게 페이지 크기를 10, 필드를 createdAt으로 정렬한다

게시물의 제목을 검색할 수 있게 해두었다

@Repository
class PostRepositoryImpl : QueryDslSupport(), PostRepositoryCustom {

    private val post = QPost.post

    override fun findByPostPage(pageable: Pageable, title: String?): Page<Post> {

        val whereClause = BooleanBuilder()
        title?.let { whereClause.and(post.title.like("%$title%")) }

        val totalCount = queryFactory
            .select(post.count())
            .from(post)
            .where(whereClause)
            .fetchOne() ?: 0L

        val content = queryFactory
            .selectFrom(post)
            .where(whereClause)
            .offset(pageable.offset)
            .limit(pageable.pageSize.toLong())
            .orderBy(*getOrderSpecifier(pageable, post))
            .fetch()

        return PageImpl(content, pageable, totalCount)
    }

    private fun getOrderSpecifier(
        pageable: Pageable,
        path: EntityPathBase<*>
    )
        : Array<OrderSpecifier<*>> {
        val pathBuilder = PathBuilder(path.type, path.metadata)

        return pageable.sort.toList().map { order ->
            OrderSpecifier(
                if (order.isAscending) Order.ASC else Order.DESC,
                pathBuilder.get(order.property)
                    as Expression<Comparable<*>>
            )
        }.toTypedArray()
    }
}

totalCount는 post 테이블에서 조건에 맞는 총 게시물 수를 가져온다

.where(whereClause)에서 where은 조건문이므로 whereClause 조건을 적용한다

fetchOne을 사용하여 단일 결과를 가져온다

결과가 없으면 null을 반환할 수 있어 기본값을 0L로 지정한다

 

content는 post 테이블에서 모든 칼럼은 선택하고
whereClause 조건을 적용한다
그리고 pageable.offset을 시작 지점으로 설정하고
pageable.pageSize 만큼 데이터를 가져올 수 있도록 해놓았다
그리고 정렬 조건에 getOrderSpecifier 함수를 넣어 이 조건에 맞게 정렬할 수 있게 해놓았다

 

getOrderSpecifier은 사실 이해가 아직 잘 가지 않아 강의에서 이렇게 하라 해서 넣었다
어떤 역할인지는 알고 있지만 설명이 잘 안된다
이 부분은 하나하나 천천히 봐야겠다

 

내가 설명할 수 있는 만큼 적어봤다

(사실 이게 맞는지도 잘 모르겠다)

 

부트 캠프가 끝날 때까지 목표가 CRUD 정복, security 설명할 수 있을 만큼, QueryDsl 정복이다
사실 아무것도 없는 백지에서 하나하나 채워가는 게 쉽지 않다
하지만 백지이기 때문에 얻는 이득도 분명 존재하기 때문에 크게 연연하지 않을 것이다
앞으로의 내 모습이 어떨까 기대가 된다