JPQL:“case”变量的“where”子句

时间:2013-12-20 20:41:54

标签: jpa case jpql

以下JPQL查询运行没有问题:

SELECT t, CASE WHEN (e.language.language = 'en' AND e.language.country = 'GB' AND e.language.variant = '') THEN e.text ELSE '' END sortProperty FROM Glossary g JOIN g.terms t JOIN t.expressions e ORDER BY sortProperty

但以下失败:

SELECT t, CASE WHEN (e.language.language = 'en' AND e.language.country = 'GB' AND e.language.variant = '') THEN e.text ELSE '' END sortProperty FROM Glossary g JOIN g.terms t JOIN t.expressions e WHERE sortProperty = 'asdf' ORDER BY sortProperty

有这个例外:

Caused by: java.lang.IllegalArgumentException: Invalid unbound variable "sortproperty" in query.

这是查询语法中的限制吗?这可能以某种方式被规避(可能使用Criteria API)?

谢谢和最诚挚的问候, 帕斯卡

1 个答案:

答案 0 :(得分:2)

问题与CASE表达式没有直接连接,通常结果变量(在本例中为sortProperty)不能在WHERE子句中使用。这就是为什么以下是无效的JPQL:

SELECT u.firstName AS someVar FROM User u WHERE someVar = 'blaa'

Criteria API在这里没有帮助。 SQL中也存在类似的限制:

SELECT u.first_name as someAlias 
FROM users u 
-- someAlias is not known here:
WHERE someAlias = 'blaa'

应将整个条件推送到WHERE子句。