子查询中的HQL case语句

时间:2013-03-18 22:26:29

标签: hibernate hql

我正在尝试用子查询中的case语句编写一个hql查询。

select zr 
from ZipResource zr 
inner join zr.zipInflows zi 
inner join zi.toInstInflows tii 
inner join tii.toInstance ti 
where ti.state = 'COMPLETED' 
and 
ti.completedDate between :dateFrom and 
:dateTill 
and (
case when :units is not null then
( ti.toPrototype.unit in :units) end ) 
order by tii.zipInflow.zipResource.name

做这样的事是真的吗?在这个查询中,我在case语句中得到了QuerySyntaxException。 谁能解释我做错了什么?

1 个答案:

答案 0 :(得分:0)

在你的代码中:units可能是一个集合(或者像这样),因为in语句需要一个集合,如果没有,它就没有意义。但在when条件:units is not null中,:units必须只有一个值(或NULL),否则语法不正确。

如果你想检查:units是否为空,那么你需要第二个参数,例如:number_of_units,你可以检查

and (
   case when :number_of_units != 0 then
   ( ti.toPrototype.unit in :units) end ) 

顺便说一句,你的case陈述是多余的。您可以使用简单的and条件来处理它(这是值得推荐的,因为数据库在查找搜索索引时可以更好地处理和调整条件):

and :number_of_units != 0
and ti.toPrototype.unit in :units 

然后有一个更简单的可能性,因为在SQL <expression> in (NULL)中求值为false。只需做

and ti.toPrototype.unit in :units