我有一个实体,其中有一个名为date
的字段和一个名为creationDate
的字段。第一个可以为null,第二个不能为null。
现在我想从某个时间范围内获取所有项目。如果date
不为空,则使用date
。如果为空,则应使用creationDate
作为支票的备份。
为此,我正在尝试组装一个com.querydsl.core.types.Predicate
,然后可以将其传递给我的数据存储库findAll
方法。 (我正在使用Spring数据存储库)。
到目前为止我所拥有的:
QItem item = QItem.item$;
BooleanExpression predicate = new CaseBuilder()
.when(item.date.isNotNull())
.then((Predicate) item.date.between(startDate, endDate))
.otherwise(item.creationDate.between(startDate, endDate));
使用我的代码安全性时,我收到此异常:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: case near line 3, column 7 [select item$
from com.example.entities.Item item$
where case when (item$.date is not null) then (item$.date between ?1 and ?2) else (item$.creationDate between ?1 and ?2) end]; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: case near line 3, column 7 [select item$
from com.example.entities.Item item$
where case when (item$.date is not null) then (item$.date between ?1 and ?2) else (item$.creationDate between ?1 and ?2) end]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: case near line 3, column 7 [select item$
from com.example.entities.Item item$
where case when (item$.date is not null) then (item$.date between ?1 and ?2) else (item$.creationDate between ?1 and ?2) end]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
这是怎么回事?
即使出于正确的目的,我也使用CaseBuilder
吗?
致谢
答案 0 :(得分:0)
好吧,我用类似的东西替换了基于Case的谓词
Predicate withDate = new BooleanBuilder(item.date.isNotNull())
.and(item.date.between(startDate, endDate));
Predicate withoutDate = new BooleanBuilder(item.date.isNull())
.and(item.creationDate.between(startDate, endDate));
Predicate combined = new BooleanBuilder(withDate)
.or(withoutDate);
,并且有效。 我仍然会对第一种方法的问题感兴趣。
答案 1 :(得分:0)
我是否出于正确的目的使用CaseBuilder?
CaseBuilder
用于创建case
语句,例如。
SELECT CASE WHEN some_column = 'A' THEN 'It is A'
WHEN some_column = 'B' THEN 'It is B'
ELSE 'It is a different value' END AS some_alias
FROM some_table;
在case语句中的每个条件中,都指定返回值。在您的示例中,您希望有条件地选择布尔逻辑。这不是案例说明的目的。