Nested query with HQL / Hibernate

独自空忆成欢 提交于 2019-12-12 00:36:52

问题


For what I have read, in some cases it is not possible to nest subqueries in HQL / Hibernate.

Let's say that I have a table of articles with a price, that belong to a group. We want to add them all, but we can only add up to a limit per group of articles. Actually, the table is denormalized, so that we already have the maximum amount for the group in the article table.

So the SQL would be as simple as :

SELECT SUM(case when max_amount is null then price
when price<max_amount then price
else max_amount end)
FROM
(SELECT
SUM(price) as price, group_id, max_amount
FROM articles
GROUP BY group_id, max_amount
)

Obviously, my data model is more complicated, but this is my main problem.

I wonder how can I rewrite this in HQL as I guess I am not allowed to nest one subquery into the other.

Thanks everybody.


回答1:


I was reluctant to do this in this way, but after some research I could only think about using the SQL query as it is.

Something like :

String sQuery = "SELECT SUM(case when max_amount is null then price ...
final org.hibernate.SQLQuery query = session.createSQLQuery(sQuery);
List results = query.list();

I can't think about Hibernate handling that nested query with HQL.



来源:https://stackoverflow.com/questions/18729097/nested-query-with-hql-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!