JPA
jpa orderby - querydsl 사용
topgon
2022. 10. 18. 12:50
프로젝트 진행 중,
최신, 오래된, 조회수, 이름 순으로 클릭시 정렬이 이루어져야한다는 요구사항을 받았다.
QueryDsl을 사용해서 해당 문제에 접근하니 처음에 어떻게 처리하지에 대한 답답한 부분이 있었으나
아래와 같은 방식으로 해결했다.
저와 같은 문제를 가지고 있는 분들은 참고하면 도움이 될것이다.
<controller>
private static Pageable getPageable(String collectionSort) {
Pageable pageable = PageRequest.of(0,9, Sort.by("collectionId").ascending());
if ("latest".equals(collectionSort)) {
pageable = PageRequest.of(0,9, Sort.by("collectionRegDate").descending());
}
if ("old".equals(collectionSort)) {
pageable = PageRequest.of(0,9, Sort.by("collectionRegDate").ascending());
}
if ("viewCount".equals(collectionSort)) {
pageable = PageRequest.of(0,9, Sort.by("collectionViewCount").descending());
}
if ("titleName".equals(collectionSort)) {
pageable = PageRequest.of(0,9, Sort.by("collectionTitleKo").ascending());
}
return pageable;
}
<Impl>
@Override
public Page<Collection> search(CollectionSearchCondition condition, Pageable pageable) {
QueryResults<Collection> results = queryFactory
.select(collection)
.from(collection)
.where(titleKoEq(condition.getCollectionTitleKo()),
summaryKoEq(condition.getCollectionSummaryKo()),
exhibitionEq(condition.getCollectionExhibition()),
collectionCategoryEq(condition.getCollectionCategory()),
collectionYearEq(condition.getCollectionStartYear(), condition.getCollectionEndYear())
)
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.orderBy(CollectionSort(pageable))
.fetchResults();
List<Collection> content = results.getResults();
long total = results.getTotal();
return new PageImpl<>(content, pageable, total);
}
private OrderSpecifier<?> CollectionSort(Pageable page) {
//서비스에서 보내준 Pageable 객체에 정렬조건 null 값 체크
if (!page.getSort().isEmpty()) {
Sort sort = page.getSort();
for (Sort.Order order : sort) {
Order direction = order.getDirection().isAscending() ? Order.ASC : Order.DESC;
String property = order.getProperty();
switch (property) {
case "collectionRegDate":
return new OrderSpecifier<>(direction,collection.collectionRegDate); //최신, 오래된 순
case "collectionViewCount":
return new OrderSpecifier<>(direction,collection.collectionViewCount); //조회수순
case "collectionTitleKo":
return new OrderSpecifier<>(direction,collection.collectionTitleKo); //이름순
}
}
}
return new OrderSpecifier<>(Order.ASC,collection.id);
}