1. 程式人生 > >HQL子查詢報錯:org.hibernate.hql.ast.QuerySyntaxException: unexpected token...

HQL子查詢報錯:org.hibernate.hql.ast.QuerySyntaxException: unexpected token...

HQL語句:

selectcount(*) from (select stu.classId  from Student stu groupby stu.classId) t_tmp_count

執行該HQL語句一直報錯:org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 22 [selectcount(*) from (...  

反覆檢查該HQL語句,沒發現問題;執行對應的sql語句,能正確得到結果;直接上網搜這個異常,也沒得到多少有用的資訊。

最後不得已,只好用Native SQL查詢解決問題。  

解決完後馬上又想到可以用下面HQL語句解決問題  

selectcount(distinct stu.classId)  from Student  

只怪自己當時鑽牛角尖。

下班後,專門開啟《hibernate_reference.pdf》《第14章 HQL: Hibernate查詢語言》。猛然瞥見《14.13. 子查詢》小節倒數第二段:

Note that HQL subqueries can occur onlyin the selectorwhere clauses

原來“HQL子查詢只能出現在selectwhere字句中“