2013-04-25 64 views
2

我在編寫Hql查詢時遇到了問題。HQL:選擇語句以及使用'when when then'給出意外令牌錯誤

我有一個名爲MyTable的列名爲Id,Column1,Column2和Type的MySQL表。所有字段都是整數類型。

select查詢基於'Type'列中的值。如果「類型」列中的值爲0 ,則在Column1中選擇基於查詢的值。如果類型列中的值爲1,則選擇查詢將基於第2列中的值。

我已經使用'case when then'成功寫入了查詢。但是,同樣的查詢中使用的HQL查詢時給予例外

SQL查詢:

select * from MyTable where case when Type=0 then Column1=234 when Type=1 then  Column2=564 end; 

HQL查詢:

from MyTableObj obj where case when obj.type=0 then obj.column1=234 when obj.type=1 then obj.column2=564 end; 

提供了以下錯誤,

17:30:16,197 ERROR [PARSER] line 1:127: unexpected token: = 
17:30:16,198 ERROR [PARSER] line 1:134: unexpected token: end 
17:30:16,199 WARN [HqlParser] processEqualityExpression() : No expression to process! 
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: = near line 1, column 127 [from MyTableObj obj where case when obj.type=0 then obj.column1=234 when obj.type=1 then obj.column2=564 end] 
    at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54) 
    at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47) 
    at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82) 
    at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:281) 
    at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180) 
    at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:134) 
    at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101) 
    at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80) 
    at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:94) 
    at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156) 
    at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135) 
    at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1650) 

謝謝Advance

+0

我得到相同的錯誤。 DId你找到一個解決方案? – Heisenberg 2016-07-07 14:37:44

+0

@海森堡。對不起,我差點忘了上下文。它發生在3年前。 Btw Mr.Heisenberg先生你的藥品生意怎麼樣? :) – 2016-07-08 06:56:46

回答

1

我做了類似的事情,但條件的值是相同的,唯一根據數據庫中的某個值更改的是列。 這裏是一個例子:

SELECT t.* FROM table t 
WHERE CASE WHEN t.column1 = 1 
    THEN t.column2 
    ELSE t.column3 
END = 123; 

這對我有效。如果你想讓你的值(在我的例子中是123)依賴於像列一樣的條件,你也可以使用CASE語句。

檢查this example in SQL,它也應該爲HQL工作。

+0

它不適合我-ERROR:org.hibernate.hql.internal.ast.ErrorCounter - 第1行:270:期待「結束」,找到'=' 錯誤:org.hibernate.hql.internal.ast。 ErrorCounter - 第1行:270:期待「結束」,找到'=' 第1行:270:期待「結束」,找到'=' – 2016-10-20 05:29:31