[英]request working on SQL/oracle but not on java Hibernate HQL
I have the following request which work fine in oracle : 我有以下要求,可以在oracle中正常工作:
SELECT SUM(col1_sum + col2_sum + col3_sum) AS sum_total FROM (
SELECT
COUNT(CASE WHEN (col1 != 0) THEN 1 END) AS col1_sum,
COUNT(CASE WHEN (col2 IS NULL) THEN 1 END) AS col2_sum,
COUNT(CASE WHEN (col3 IS NULL OR col 3 < 0) THEN 1 END) AS col3_sum
FROM myTable)
;
It return the right sum according to all my condition 它根据我的所有条件返回正确的总和
But when I translate it into HQL like this : 但是当我像这样将其翻译成HQL时:
@Query("SELECT SUM(col1_sum + col2_sum + col3_sum) AS sum_total FROM ( "
+"SELECT "
+" COUNT(CASE WHEN (col1 != 0) THEN 1 END) AS col1_sum, "
+" COUNT(CASE WHEN (col2 IS NULL) THEN 1 END) AS col2_sum, "
+" COUNT(CASE WHEN (col3 IS NULL OR col 3 < 0) THEN 1 END) AS col3_sum "
+"FROM myTable)")
I could compile my project without error, but when I launch it, I have the following error from hibernate : 我可以毫无错误地编译我的项目,但是当我启动它时,我从hibernate中遇到了以下错误:
2018-03-08 11:18:54.485 [NO_USER NO_SESSION] ERROR ohhiaErrorCounter : line 1:96: unexpected token: ( antlr.NoViableAltException: unexpected token: ( at org.hibernate.hql.internal.antlr.HqlBaseParser.fromRange(HqlBaseParser.java:1544) [....] Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 96 [...]
Apparently hibernate do not reconize my query after the FROM (
on the first line 显然,休眠状态不会在
FROM (
第一行之后
Is there any way to correctly convert my Oracle/SQL request into Hibernate/HQL ? 有什么方法可以将我的Oracle / SQL请求正确转换为Hibernate / HQL吗?
使用SQL而不是HQL的本机查询的Hibernate批注是@NamedNativeQuery,而不是@Query。
That is because Hibernate doesn't support subquery in the FROM clause. 这是因为Hibernate在FROM子句中不支持子查询。 Refer to the discussion Cannot use subqueries in from clause.
请参考讨论不能在from子句中使用子查询。 Is there an alternativ .
是否有替代方案 。
You may need to use @NamedNativeQuery that allows you to pass Native SQL, that way you can use subquery in FROM clause or see you rewrite your query without subquery in the FROM clause. 您可能需要使用@NamedNativeQuery,它允许您传递本机SQL,这样您可以在FROM子句中使用子查询,或者看到您在FROM子句中重写查询而没有子查询。
Thanks for your answer, I have found a way to do it without using @NamedNativeQuery. 感谢您的回答,我找到了一种无需使用@NamedNativeQuery的方法。 I had refactor my SQL query and apparently now Hibernate understand it correctly.
我已经重构了SQL查询,显然现在Hibernate正确理解了它。
Now, on my java code, the query look like : 现在,在我的Java代码上,查询如下所示:
@Query("SELECT ((COUNT(CASE WHEN (col1 != 0) THEN 1 END)) + "
+ "(COUNT(CASE WHEN (col2 IS NULL) THEN 1 END)) + "
+ "(COUNT(CASE WHEN (col3 IS NULL OR col3 < 0) THEN 1 END))) AS total "
+ "FROM myTable")
It's work fine with that. 这样很好。 I think the issue was not the subquery in my requset (I have other request with subquery which work fine) but the "SUM" keyword.
我认为问题不是我的requset中的子查询(我对子查询有其他要求,可以正常工作),但不是关键字“ SUM”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.