I met a problem with SQL.
Assume this is my native SQL:
SELECT * FROM products
ORDER BY balance <= bottleneck DESC, product_code ASC
This is working at postgressql. But it doesn’t work with HQL. My HQL as following:
from Products as p order by p.balance < p.bottleneck desc, p.productCode asc
And I met exception as following:
Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: < near line 1, column 67 [from com.inventory.inventory.vo.Products as p order by p.balance < p.bottleneck]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:261)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1760)
at com.inventory.inventory.dao.impl.ProductsDAOImpl.getProducts(ProductsDAOImpl.java:72)
at Main.main(Main.java:43)
Is any way to solve for this query?
Your help is much appreciated.
Thanks,
Best rgds,
A1ucard
I haven’t got Hibernate installed right now, but this should work:
This is a more “standard” way of writing SQL because you put order after the where clause.
Edit:
There doesn’t seem to be a way to do what you want, at least not using HQL. Postgres has a much more powerful ORDER BY clause than HQL has.
Postgres documentation on select clause has “ORDER BY expression“, where expression has it’s own documentation page.
On the other hand, Hibernate’s order by clause is very limited. It allows you to order columns and use regular or aggregate functions.
The deal killer is this sentence:
So, it seems you are out of luck and you must use native SQL if you want to obtain a resultset that you need.