How to sort by querydsl alias

主宰稳场 提交于 2021-02-07 03:51:40

问题


Is there a way to sort repository query results by querydsl alias?

So far I've managed to filter, but sorting results with an error:

org.springframework.data.mapping.PropertyReferenceException: No property username found for type User!

request:

GET /users?size=1&sort=username,desc

my rest controller method:

@GetMapping("/users")
public ListResult<User> getUsersInGroup(
        @ApiIgnore @QuerydslPredicate(root = User.class) Predicate predicate,
        Pageable pageable) {
    Page<User> usersInGroup =
            userRepository.findByGroup(CurrentUser.getGroup(), predicate, pageable);
    return new ListResult<>(usersInGroup);
}

my repository:

@Override
default void customize(QuerydslBindings bindings, QUser root) {
    bindings.including(root.account.login, root.account.firstName, root.account.lastName,
            root.account.phoneNumber, root.account.email, root.account.postalCode, root.account.city,
            root.account.address, root.account.language, root.account.presentationAlias);
    bindAlias(bindings, root.account.login, "username");
}

default Page<User> findByGroup(Group group, Predicate predicate, Pageable pageable) {
    BooleanExpression byGroup = QUser.user.group.eq(group);
    BooleanExpression finalPredicate = byGroup.and(predicate);
    return findAll(finalPredicate, pageable);
}

default void bindAlias(QuerydslBindings bindings, StringPath path, String alias) {
    bindings.bind(path).as(alias).first(StringExpression::likeIgnoreCase);
}

I've also tried to implement my own PageableArgumentResolver based on QuerydslPredicateArgumentResolver, but some of the methods used there are package private so I thought maybe I am going in the wrong direction


回答1:


I succeeded by creating a PageableArgumentResolver annotated with class type of query root class and adding alias registry to my generic repository interface.

This solution seems like a workaround but at least it works ;)

repository:

public interface UserRepository extends PageableAndFilterableGenericRepository<User, QUser> {

QDSLAliasRegistry aliasRegistry = QDSLAliasRegistry.instance();

@Override
default void customize(QuerydslBindings bindings, QUser root) {
    bindAlias(bindings, root.account.login, "username");
}

default void bindAlias(QuerydslBindings bindings, StringPath path, String alias) {
    bindings.bind(path).as(alias).first(StringExpression::likeIgnoreCase);
    aliasRegistry.register(alias, path);
}

alias registry:

public class QDSLAliasRegistry {

private static QDSLAliasRegistry inst;

public static QDSLAliasRegistry instance() {
    inst = inst == null ? new QDSLAliasRegistry() : inst;
    return inst;
}

private QDSLAliasRegistry() {
    registry = HashBiMap.create();
}

HashBiMap<String, Path<?>> registry;

resolver:

public class QDSLSafePageResolver implements PageableArgumentResolver {

private static final String DEFAULT_PAGE = "0";
private static final String DEFAULT_PAGE_SIZE = "20";
private static final String PAGE_PARAM = "page";
private static final String SIZE_PARAM = "size";
private static final String SORT_PARAM = "sort";
private final QDSLAliasRegistry aliasRegistry;

public QDSLSafePageResolver(QDSLAliasRegistry aliasRegistry) {
    this.aliasRegistry = aliasRegistry;
}

@Override
public boolean supportsParameter(MethodParameter parameter) {
    return Pageable.class.equals(parameter.getParameterType())
            && parameter.hasParameterAnnotation(QDSLPageable.class);
}

@Override
public Pageable resolveArgument(MethodParameter parameter,
                                ModelAndViewContainer mavContainer,
                                NativeWebRequest webRequest,
                                WebDataBinderFactory binderFactory) {

    MultiValueMap<String, String> parameterMap = getParameterMap(webRequest);

    final Class<?> root = parameter.getParameterAnnotation(QDSLPageable.class).root();
    final ClassTypeInformation<?> typeInformation = ClassTypeInformation.from(root);

    String pageStr = Optional.ofNullable(parameterMap.getFirst(PAGE_PARAM)).orElse(DEFAULT_PAGE);
    String sizeStr = Optional.ofNullable(parameterMap.getFirst(SIZE_PARAM)).orElse(DEFAULT_PAGE_SIZE);
    int page = Integer.parseInt(pageStr);
    int size = Integer.parseInt(sizeStr);
    List<String> sortStrings = parameterMap.get(SORT_PARAM);
    if(sortStrings != null) {
        OrderSpecifier[] specifiers = new OrderSpecifier[sortStrings.size()];

        for(int i = 0; i < sortStrings.size(); i++) {
            String sort = sortStrings.get(i);
            String[] orderArr = sort.split(",");
            Order order = orderArr.length == 1 ? Order.ASC : Order.valueOf(orderArr[1].toUpperCase());
            specifiers[i] = buildOrderSpecifier(orderArr[0], order, typeInformation);
        }

        return new QPageRequest(page, size, specifiers);
    } else {
        return new QPageRequest(page, size);
    }
}

private MultiValueMap<String, String> getParameterMap(NativeWebRequest webRequest) {
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();

    for (Map.Entry<String, String[]> entry : webRequest.getParameterMap().entrySet()) {
        parameters.put(entry.getKey(), Arrays.asList(entry.getValue()));
    }
    return parameters;
}

private OrderSpecifier<?> buildOrderSpecifier(String sort,
                                              Order order,
                                              ClassTypeInformation<?> typeInfo) {


    Expression<?> sortPropertyExpression = new PathBuilderFactory().create(typeInfo.getType());
    String dotPath = aliasRegistry.getDotPath(sort);
    PropertyPath path = PropertyPath.from(dotPath, typeInfo);
    sortPropertyExpression = Expressions.path(path.getType(), (Path<?>) sortPropertyExpression, path.toDotPath());

    return new OrderSpecifier(order, sortPropertyExpression);
}
}


来源:https://stackoverflow.com/questions/44949660/how-to-sort-by-querydsl-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!