gpt4 book ai didi

java - QueryDSL 按计算字段排序

转载 作者:行者123 更新时间:2023-12-02 09:14:31 31 4
gpt4 key购买 nike

在我们的应用程序中,我们使用 querydsl 来获取实体并将它们转换为表示对象。该表示对象具有名为active 的字段。这是由实体的某个日期是在今天之前(active = false)还是在今天之后(active = true)决定的。这样做一切都很顺利。问题是当尝试按该表达式(QEntity.someDate > Today)进行排序时。这使得 hibernate 抛出此错误:

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: > near line 3, column 40 [select object.someField as someAlias, (object.someDate > ?1) as active, object as objectAlias
from com.example.Object object
order by object.someDate > ?1 asc]

我创建 OrderSpecifier 如下:

    @Override
public OrderSpecifier<?> getOrderByClause(SortKey sortKey) {
BooleanExpression expression = getBooleanPath(); // This is the expression: (object.someDate > ?1)
if (sortKey.getSortOrder() == ESortOrder.ASCENDING) {
return new OrderSpecifier(Order.ASC, expression);
}
return new OrderSpecifier(Order.DESC, expression);
}

我也尝试过这样的:

    @Override
public OrderSpecifier<?> getOrderByClause(SortKey sortKey) {
BooleanExpression expression = getBooleanPath();
if (sortKey.getSortOrder() == ESortOrder.ASCENDING) {
return new CaseBuilder().when(expression.isFalse()).then(1).otherwise(2).asc();
}
return new CaseBuilder().when(expression.isTrue()).then(1).otherwise(2).desc();
}

这会导致类似的错误:

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: > near line 3, column 40 [select object.someField as someAlias, (object.someDate > ?1) as active, object as objectAlias
from com.example.Object object
order by case when (object.someDate > ?1 = ?2) then ?3 else 2 end asc]

最后是这样的:

    @Override
public OrderSpecifier<?> getOrderByClause(SortKey sortKey) {
BooleanExpression expression = getBooleanPath();
if (sortKey.getSortOrder() == ESortOrder.ASCENDING) {
return new CaseBuilder().when(expression.eq(true)).then(1).otherwise(2).asc();
}
return new CaseBuilder().when(expression.eq(true)).then(1).otherwise(2).desc();
}

这会引发与之前相同的错误

最佳答案

通过创建如下所示的 order 子句来修复它:

    @Override
public OrderSpecifier<?> getOrderByClause(SortKey sortKey) {
BooleanPath path = getBooleanPath();
if (sortKey.getSortOrder() == ESortOrder.ASCENDING) {
return path.asc();
}
return path.desc();
}

private BooleanPath getBooleanPath() {
return Expressions.booleanPath(getFieldName());
}

其中字段名称是字符串形式的别名,在我们的例子中为“active”。

关于java - QueryDSL 按计算字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59106196/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com