今天写一个稍微复杂的Hibernate 查询,在启动项目的时候报错:Antlr.Runtime.NoViableAltException:Unexpected token: from
意思很明显,是hql语句有问题,语句如下:
@NamedQuery(name = "Detect.CountByUnitAndResultDx",
query = "select "
+ "a.detectUnitId, "
+ "count(*) as total, "
+ "(select count(*) from Detect a where a.resultDx = 0 and a.detectUnitId =:detectUnitId) as bad, "
+ "(select count(*) from Detect a where a.resultDx = 1 and a.detectUnitId =:detectUnitId) as good, "
+ "from Detect a "
+ "where a.detectUnitId = :detectUnitId")
一开始,以为是hql语法有问题,因为对hql不是很熟悉,所以有些疑惑,尝试了几种修改,都不起作用。
换个思路既然提示“from”有问题,那就看看from:句子中有3处,逐一进行排查。
第一处,是第一个select子句,前后完全看不出什么问题。
第二处,是第二个select子句,前后也完全看不出什么问题,是标准的写法。
第三处,是最外层的from,似乎也看不出什么问题。等等!往前看,这个from的前面一点:“ ... as good,”,此处有个逗号,引起了注意:
sql中选择若干字段,用逗号分隔,但最后一个字段的后面是没有逗号的!
于是删除第三个from前面的逗号,也就是 “as good”后面那个逗号,重新启动项目,没报错,问题解决!
原来,这个错误和hql无关,是最基础的sql的语法问题!