连接中的HQL子查询

时间:2009-07-17 07:05:06

标签: hibernate hql

我有一个Order类,它包含一组OrderSection,它本身包含一组OrderItem。

在SQL中,可以在JOIN子句中使用SELECT语句,如以下查询中所述:

SELECT
    o.id,
    o.amount,
    sum(s.quantity*s.price),
    sum(s.quantity*i.price)
FROM
    orders AS o
    JOIN ordersections AS s ON s.order_id=o.id
    JOIN (SELECT section_id, sum(quantity*price) AS price FROM orderitems GROUP BY section_id) AS i ON i.section_id=s.id
GROUP BY o.id, o.amount

是否可以在HQL中表达这样的查询?

1 个答案:

答案 0 :(得分:2)

除非我遗漏了某些内容,否则您的查询可以在SQL中重写为:

SELECT
  o.id,
  o.amount,
  sum(s.quantity*s.price),
  sum(s.quantity*i.quantity*i.price)
FROM orders AS o
  JOIN ordersections AS s ON s.order_id=o.id
  JOIN orderitems AS i ON i.section_id=s.id
GROUP BY o.id, o.amount

在这种情况下,可以在HQL中将其重写为:

SELECT
  o.id,
  o.amount,
  sum(s.quantity*s.price),
  sum(s.quantity*i.quantity*i.price)
FROM orders AS o
  JOIN o.sections AS s
  JOIN s.items AS i
GROUP BY o.id, o.amount

如果我遗漏了某些内容并且上述查询没有返回您想要的内容,那么因为Subqueries in HQL can only occur in SELECT or WHERE clauses而导致HQL转换失败。但是,您可以将查询映射为<sql-query> - 最后应该没有任何区别。