来自字符串的JPA / HQL本机查询

时间:2014-01-14 09:57:15

标签: java sql hibernate jpa hql

例如,我将此查询部分作为预定义的临时文件。

String temp = "select st from xxxx st where "

稍后会有if else运算符。

if (c>v)temp += "yyy is null";
else temp += "yyy = 2";
Query query = em.createNativeQuery(temp);

堆栈跟踪异常:

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query

也许我做错了?

3 个答案:

答案 0 :(得分:0)

where语句中的多个子句由and分隔:

else temp += " and yyy = 2"

本机SQL查询也不使用select子句中的别名来选择他们使用的所有列*

String temp = "select * from xxxx st where "

答案 1 :(得分:0)

尝试这样,只需将yyy变量放在if条件中,因为它在查询中重复

String temp = "select st from xxxx st where "

if (c>v)
    temp += "yyy is null";
else 
    temp += "yyy = 2"

Query query = em.createNativeQuery(temp);

答案 2 :(得分:0)

我想这是因为您在st.之前忘记了yyy标识符 或者可能是因为您只选择st,但应选择st.*

应为select st.* from xxxx st where st.yyy is null

请使用hibernate属性show_sql = true跟踪生成的SQL并在此处发布

相关问题