HQL案例当错误意外AST节点:CASE在第1行附近

时间:2018-04-24 00:35:36

标签: java sql hibernate hql

我的存储库中有一个查询。

@Query(Constant.QUERY)
List<Guide> findGuide(@Param("locationName") String locationName, @Param("gender") String gender, @Param("type") String type, @Param("language") String language);

和Constant.QUERY是

public static final String QUERY_FIND_GUIDE = "SELECT g.id FROM Guide g " + 
        " LEFT JOIN g.user u  " + 
        " LEFT JOIN g.locations l " + 
        " LEFT JOIN g.languages lang "+
        "WHERE (UPPER(:locationName)=UPPER('NULL') OR :locationName IS NULL OR :locationName ='' OR l.locationName = :locationName) "
        + " AND (UPPER(:gender)=UPPER('NULL') OR :gender IS NULL OR :gender ='' OR g.gender =:gender) "
        + " AND (:type IS NULL OR :type ='' OR "
        + " (CASE WHEN UPPER(:type)=UPPER('NULL') THEN (g.cardnumber IS NULL) ELSE (g.cardnumber IS NOT NULL) END) )"
        + " AND (UPPER(:language)=UPPER('NULL') OR :language IS NULL OR :language='' OR lang.language = :language)";

当我运行Page时出现错误:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: CASE near line 1, column 376 [SELECT g.id FROM com.webapp.tgo.entities.Guide g  LEFT JOIN g.user u   LEFT JOIN g.locations l  LEFT JOIN g.languages lang WHERE (UPPER(:locationName)=UPPER('NULL') OR :locationName IS NULL OR :locationName ='' OR l.locationName = :locationName)  AND (UPPER(:gender)=UPPER('NULL') OR :gender IS NULL OR :gender ='' OR g.gender =:gender)  AND (:type IS NULL OR :type ='' OR  (CASE WHEN UPPER(:type)=UPPER('NULL') THEN (g.cardnumber IS NULL) ELSE (g.cardnumber IS NOT NULL) END) ) AND (UPPER(:language)=UPPER('NULL') OR :language IS NULL OR :language='' OR lang.language = :language)]

我认为&#34; IS NULL&#34;在&#34; THEN&#34;之后无法使用结果,这是真的吗?如果错误请帮助我检查这个错误:(

2 个答案:

答案 0 :(得分:0)

我不认为HQL(或任何其他版本的SQL)会让您使用CASE表达式,就像尝试使用它一样。但是,我们可以将您的逻辑改写为:

WHERE
    (UPPER(:locationName) = UPPER('NULL') OR :locationName IS NULL OR
        :locationName = '' OR l.locationName = :locationName) AND
    (UPPER(:gender) = UPPER('NULL') OR :gender IS NULL OR :gender = '' OR
        g.gender = :gender) AND
    (:type IS NULL OR :type = '' OR
        ((UPPER(:type) = UPPER('NULL') AND g.cardnumber IS NULL) OR
        g.cardnumber IS NOT NULL) AND
    UPPER(:language) = UPPER('NULL') OR :language IS NULL OR :language = '' OR
    lang.language = :language)

我的答案的关键是跟随CASE表达式:

CASE WHEN UPPER(:type) = UPPER('NULL')
     THEN (g.cardnumber IS NULL)
     ELSE (g.cardnumber IS NOT NULL) END

被重写为:

(UPPER(:type) = UPPER('NULL') AND g.cardnumber IS NULL) OR g.cardnumber IS NOT NULL

答案 1 :(得分:0)

QuerySyntaxException可能由以下原因引起:

  1. 你没有在Hibernate.cfg.xml中编写映射。
  2. 您已在Hibernate.cfg.xml中编写了映射,但它出错了。
  3. 检查字段名称是否使用数据库中的关键字。