使用SELECT CASE WHEN

时间:2016-04-20 08:42:10

标签: java hibernate jpa

我正在尝试运行此命名查询,如果找到符合WHERE条件的记录,则返回1:

SELECT CASE WHEN EXISTS
(SELECT p
    FROM Books p
    WHERE bookNum = :bookNum
        AND author = :author
        AND bookID <> :bookID)
THEN 1
ELSE NULL
END

我使用EXISTS使其更快但我在 TOMCAT SERVER START 上出现此错误。

  

org.hibernate.hql.ast.QuerySyntaxException:意外的子树结束   [EXISTS时选择案例(SELECT p FROM com.userclasses.Books p WHERE   bookNum =:bookNum AND author =:author AND bookID&lt;&gt; :bookID)那么1   ELSE NULL END] at   org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)     在   org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)     在   org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)     在   org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:261)     在   org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)     在   org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)     在   org.hibernate.engine.query.HQLQueryPlan。(HQLQueryPlan.java:101)     在   org.hibernate.engine.query.HQLQueryPlan。(HQLQueryPlan.java:80)     在   org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)     在   org.hibernate.impl.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:549)     在   org.hibernate.impl.SessionFactoryImpl。(SessionFactoryImpl.java:413)     在   org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)     在   org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)

我运行了下面的代码来获取hibernate版本,正如它在this link中所说的那样:它被修复了:

System.out.println(org.hibernate.Version.getVersionString());
System.out.println("Hibernate Version: "+ org.hibernate.annotations.common.Version.VERSION);

它在控制台中告诉我

3.6.4.Final
Hibernate Version: 3.2.0.Final

1 个答案:

答案 0 :(得分:0)

这解决了它

SELECT CASE WHEN EXISTS
(SELECT p
    FROM Books p
    WHERE bookNum = :bookNum
    AND author = :author
    AND bookID <> :bookID)
THEN 1
ELSE NULL
END FROM Books p

但是添加FROM Books p将不会提高性能,因为它现在将返回列表,而不是单个记录:(