JPA Criteria Query API并且最后按null排序 [英] JPA Criteria Query API and order by null last

查看:1279
本文介绍了JPA Criteria Query API并且最后按null排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是空值必须是最后一个按语句排序。我的代码在下面拍了一下。我使用javax持久标准构建器。我的查询很复杂。

My problem is null values must be last order by statement. My code snipshot below. I use javax persistance criteria builder. My query complicated.

import javax.persistence.criteria.CriteriaBuilder;

public Predicate getSomePredicate() {
    Predicate predicate = cb.conjunction();....

    ...predicate.getExpressions().add(cb.and(cb.or(cb.and(v1, v2), cb.and(s1, s2))));

    EOrderByType orderType = EOrderByType.values()[orderBy]
            ;
    switch (orderType) {
    case PRICE: cq.where(predicate).orderBy(cb.asc(root.get("price")));
        break;
    case PRICE_HIGH_TO_LOW: cq.where(predicate).orderBy(cb.desc(root.get("price")));
        break;
    case CONSUPTION: cq.where(predicate).orderBy(cb.desc(root.get("consume")));
        break;
    default:
        break;
    }

    return cq.getRestriction();
}

如何使用条件构建器按价格实现空订单?

How to achieve order by price null last with criteria builder ?

推荐答案

您好我几乎搜索所有互联网页面然后找到解决方案,您可以按部分编写开关案例顺序。如下所示:如果价格为空,则按desc订购,价格值为1000000,如果价格为空则按asc订购,价格值为0.如果你想要这些,你可以写下面的表达式。

Hi I almost search all internet pages and then find a solution, you can write switch case order by part. like below: to order by desc if price is null, price value is 1000000, and to order by asc if price is null, price value is 0. if you want these, you can write expression like below.

                EOrderByType orderType = EOrderByType.values()[orderBy];                    
                Expression<Object> queryCase = cb.selectCase().when(cb.isNull(root.get("price")), 100000000).otherwise(root.get("price"));
                Direction dir = Direction.ASC;

                switch (orderType) {
                    case UCUZDAN_PAHALIYA:
                        queryCase = cb.selectCase().when(cb.isNull(root.get("price")), 100000000).otherwise(root.get("price"));
                        break;
                    case PAHALIDAN_UCUZA:
                        queryCase = cb.selectCase().when(cb.isNull(root.get("price")), 0).otherwise(root.get("price"));
                        dir = Direction.DESC;
                        break;
                }

                  cq.where(predicate).orderBy(direction( cb, queryCase, dir));

这篇关于JPA Criteria Query API并且最后按null排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆