org.springframework.data.jpa.support.PageableUtils Maven / Gradle / Ivy
package org.springframework.data.jpa.support;
import java.lang.reflect.Field;
import java.util.Map;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.querydsl.QSort;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
public class PageableUtils {
public static boolean pageable(Pageable pageable, String property) {
if (pageable != null && pageable.getSort() != null && StringUtils.hasText(property)) {
for (Order order : pageable.getSort()) {
if (property.equalsIgnoreCase(order.getProperty())) {
return true;
}
}
}
return false;
}
public static Pageable pageable(Pageable pageable, Map> expressions) {
if (pageable != null && pageable.getSort() != null && !CollectionUtils.isEmpty(expressions)) {
Sort sort = null;
for (Order order : pageable.getSort()) {
if (expressions.containsKey(order.getProperty())) {
OrderSpecifier orderSpecifier;
switch (order.getDirection()) {
case ASC:
orderSpecifier = expressions.get(order.getProperty()).asc();
break;
case DESC:
orderSpecifier = expressions.get(order.getProperty()).desc();
break;
default:
throw new UnsupportedOperationException();
}
switch (order.getNullHandling()) {
case NATIVE:
break;
case NULLS_FIRST:
orderSpecifier = orderSpecifier.nullsFirst();
break;
case NULLS_LAST:
orderSpecifier = orderSpecifier.nullsLast();
break;
default:
throw new UnsupportedOperationException();
}
sort = sort == null ? new QSort(orderSpecifier) : sort.and(new QSort(orderSpecifier));
}
}
if (sort != null) {
Field field = ReflectionUtils.findField(pageable.getClass(), "sort");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, pageable, sort);
}
}
return pageable;
}
/**
* @see java.util.TreeMap
* @see java.lang.String#CASE_INSENSITIVE_ORDER
*/
public static Pageable pageable(Pageable pageable, ComparableExpressionBase... expressions) {
Map> map = new LinkedCaseInsensitiveMap>();
for (ComparableExpressionBase expression : expressions) {
map.put(String.valueOf(expression), expression);
}
return pageable(pageable, map);
}
public static Pageable pageable(Pageable pageable, Sort sort) {
if (pageable != null && sort != null) {
Field field = ReflectionUtils.findField(pageable.getClass(), "sort");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, pageable, sort);
}
return pageable;
}
}