코틀린에서 Querydsl을 이용하여 pageble객체를 받아 동적으로 정렬하기 위해서 유틸리티 하나를 생성한다.
open class QuerydslUtils {
fun <T, Q : EntityPath<*>> JPAQuery<T>.withPageable(pageable: Pageable, entityPath: Q): JPAQuery<T> {
val query = this.limit(pageable.pageSize.toLong()).offset(pageable.offset)
for (o in pageable.sort) {
val pathBuilder = PathBuilder<Any?>(entityPath.type, entityPath.metadata)
query.orderBy(
OrderSpecifier(
if (o.isAscending) Order.ASC else Order.DESC,
pathBuilder.get(o.property) as Expression<out Comparable<*>>
)
)
}
return query
}
}
사용하고자 하는 Querydsl 코드에서 QuerysUtils를 상속받고
.withPageable로 사용하면된다. 인자로 pageable, Q객체의 엔티티를 보내주자
import com.exemple.entity.QAcademy.academy
class academyDaoCustomImpl : AcademyDaoCustom, QuerydslUtils() {
override fun findBySearchPage(condition: SearchCondition, pageable: Pageable): Page<Academy> {
val query = queryFactory.selectFrom(academy)
.where(
academyNameContains(condition.academyName),
academyPlanEQ(condition.plan),
dateBetween(condition.startDate,condition.endDate),
academy.deleted.isFalse,
)
.withPageable(pageable, academy)
val content = query.fetch()
//이하 카운트쿼리 분리 생략
}
}
이로써 여러곳에서 쉽게 pageable을 사용할 수 있다.
'Programing > Spring Boot' 카테고리의 다른 글
| 오류) Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. (0) | 2023.08.28 |
|---|---|
| 동시성 문제 해결 - 비관적 락 (Pessimistic Lock) (0) | 2023.08.03 |
| 스프링부트 스케줄러가 여러번 실행된다면? @SchedulerLock 사용법 (0) | 2023.07.06 |
| SpringBoot @RequestBody 데이터 선택적으로 받기 (0) | 2023.07.04 |
| 코틀린 스프링부트 Querydsl 사용 예제 (0) | 2023.07.03 |