Java Hibernate使用case时,在hql

时间:2016-12-27 06:11:54

标签: java mysql hibernate hql

使用此查询:

需要获得其中rank不等于0的keywordIds的最低排名searchengine是“xyz.com”,如果keywordId没有除0以外的等级,那么它应该显示为10000

TrackId | KeywordId | SearchEngine | 排名

1 | 101 | xyz.com | 0

1 | 101 | xyz.com | 55

1 | 101 | xyz.com | 12

2 | 201 | xyz.com | 1

2 | 201 | xyz.com | 98

2 | 201 | xyz.com | 23

3 | 301 | xyz.com | 0

3 | 301 | xyz.com | 0

结果应该是:

min Rank

12

1

10000

当我使用hql查询时,我得到的结果是异常:

bestRanks[i] = (List<Integer>)getHibernateTemplate().findByNamedParam("Select min(case when Rank > 0 then Rank else 10000 end) from Serpstrackhistory t where t.keywordId in (:KeywordId) and t.searchEngine=(:SearchEngine) group by KeywordId ORDER BY FIELD(KeywordId,t.keywordId in (:KeywordIds))",new String[]{"KeywordId", "SearchEngine", "KeywordIds"}, new Object[]{keywordId ,searchEngine[i], keywordId});

例外:

java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.AggregateNode 
 \-[AGGREGATE] AggregateNode: 'min'
    \-[CASE] CaseNode: 'case'
       +-[WHEN] SqlNode: 'when'
       |  +-[GT] BinaryLogicOperatorNode: '>'
       |  |  +-[IDENT] IdentNode: 'Rank' {originalText=Rank}
       |  |  \-[NUM_INT] LiteralNode: '0'
       |  \-[IDENT] IdentNode: 'Rank' {originalText=Rank}
       \-[ELSE] SqlNode: 'else'
          \-[NUM_INT] LiteralNode: '10000'

当我使用原始查询时,我得到的结果是正确的:

SELECT min(case when Rank > 0 then Rank else 10000 end) FROM `serpstrackhistory` WHERE  KeywordId in (1,2,3) and SearchEngine="xyz.com" group by KeywordId

请帮助我知道我的hql查询中有什么不正确。

1 个答案:

答案 0 :(得分:1)

请尝试使用别名查询 -

min(case when t.Rank > 0 then t.Rank else 10000 end)