[英]QueryDsl orderBy some enums and date
I need a way to sort based on date, with all rows of a certain type to be grouped last (but also sorted by date).我需要一种基于日期排序的方法,最后将某种类型的所有行分组(但也按日期排序)。
For instance, suppose I have a DB column where values can take on ["A", "B", "C"].例如,假设我有一个 DB 列,其中的值可以采用 [“A”、“B”、“C”]。 In the same table, there is also a dateCreated column.
在同一个表中,还有一个 dateCreated 列。
I want all rows with "A" to be last and all rows (including those within group A) to be sorted by date created (ascending for simplicity sake)我希望所有带有“A”的行都放在最后,并且所有行(包括 A 组中的行)都按创建日期排序(为简单起见,升序)
For instance, if I had the rows:例如,如果我有以下行:
ID ![]() |
enum![]() |
dateCreated![]() |
---|---|---|
1 ![]() |
A![]() |
2020-01-01 ![]() |
2 ![]() |
A![]() |
2020-01-03 ![]() |
3 ![]() |
A![]() |
2020-01-02 ![]() |
4 ![]() |
B![]() |
2020-02-03 ![]() |
5 ![]() |
B![]() |
2020-02-01 ![]() |
6 ![]() |
C ![]() |
2020-02-02 ![]() |
The resulting order should be:结果顺序应该是:
5,6,4,1,3,2
To explain, all of the non-A rows come first, ordered by date.解释一下,所有非 A 行都排在第一位,按日期排序。 Then all of the A rows, also ordered by date.
然后是所有 A 行,也按日期排序。
I see the SO post QueryDsl orderBy specific string values which almost provides what I need, but it is unfortunately not nuanced enough for my use case.我看到 SO post QueryDsl orderBy specific string values这几乎提供了我需要的东西,但不幸的是它对于我的用例来说不够细致。
You can order by a boolean expresion.您可以通过 boolean 表达式订购。 Booleans order false to true naturally, so you can just sort ascending.
布尔值自然地将 false 排序为 true,因此您可以按升序排序。
.orderBy(enum.eq("A").asc(), created.asc())
I ended up finding a working solution with something like:我最终找到了一个可行的解决方案,例如:
private OrderSpecifier<Integer> orderByEnum() {
NumberExpression<Integer> cases = new CaseBuilder()
.when(QTable.table.enum.eq("A"))
.then(2)
.otherwise(1);
return new OrderSpecifier<>(Order.ASC, cases);
}
I added that to a order specifier array like so:我将它添加到订单说明符数组中,如下所示:
OrderSpecifier<?>[] order = new OrderSpecifier[] {
orderByEnum(),
QTable.table.dateCreated.asc()
};
And then I passed the order specifier array to the query with然后我将订单说明符数组传递给查询
queryFactory.select(...)
.from(...)
.where(...)
.orderBy(order);
It looks like this got me what I needed.看起来这让我得到了我需要的东西。 Just had to break the problem down into individual components and add that to an order specifier array.
只需将问题分解为单个组件并将其添加到顺序说明符数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.