【问题标题】:QueryDsl orderBy specific string valuesQueryDsl orderBy 特定字符串值
【发布时间】:2021-07-30 11:28:51
【问题描述】:

我需要按三个不同的字符串对我的数据库响应进行排序。
字段只能采用这四个值"A", "B", "C", null
有没有办法按自定义顺序对数据进行排序,同时使用 QueryDsl 从数据库中检索数据?

customOrder = ["B", "A", "C"]

【问题讨论】:

    标签: java spring sorting jpa querydsl


    【解决方案1】:

    解决方案是使用CASE 为案例分配编号,并使用ASC/DESC 对这些编号进行排序。

    SQL 中的解决方案:

    SELECT *
    FROM table
    ORDER BY CASE 
       WHEN field = 'B' THEN 1,
       WHEN field = 'A' THEN 2,
       WHEN field = 'C' THEN 3
       ELSE 4
       END
    

    解决方案:

    private OrderSpecifier<Integer> provideStatusOrder() {
            NumberExpression<Integer> cases = new CaseBuilder()
                                                      .when(field.eq("B"))
                                                      .then(1)
                                                      .when(field.eq("C"))
                                                      .then(2)
                                                      .when(field.eq("A"))
                                                      .then(3)
                                                      .otherwise(4);
            return new OrderSpecifier<>(Order.ASC, cases);
    }
    

    用法:

    return query.orderBy(provideStatusOrder())
                .fetch();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多