无法使用内部联接形成HQL查询,结果有多个实体

时间:2013-07-28 04:33:48

标签: sql spring hibernate postgresql hql

我需要形成一个HQL查询,返回多个看起来像这样的实体对象:

/*
 * Want to return both H and C in the same query...
 */
SELECT H, C
/*
 * ... such that H is the most recent entry...
 *
 * (Note that 'ON' keyword does not work with HQL)
 */
FROM HealthHistory H INNER JOIN (
    SELECT id, MAX(insertion_time) insertion_time
    FROM HealthHistory
    GROUP BY id
) IH ON H.id = IH.id AND IH.insertion_time = H.insertion_time
/*
 * ... while getting these other entities involved...
 */
LEFT JOIN NodeA A
LEFT JOIN NodeC C
LEFT JOIN NodeL L
/*
 * ... so we can add some more expressions here...
 */
WHERE A.someId = C.descendant.id -- A -> C
  AND A.something = someConstant
  AND C.someId = L.id -- C -> L
  AND C.something = someConstant
  AND L.something = someConstant
  AND H.someId = C.id -- H -> C
  AND H.something = someConstant

我一直在接收org.hibernate.hql.ast.QuerySyntaxException: unexpected token: {(, A, ON, or INNER}

我已经挣扎了很长一段时间,即使在查看了很多类似的问题之后。对此有任何帮助表示赞赏...

2 个答案:

答案 0 :(得分:0)

对于HQL,您不需要开启,您可以找到它here for more info

Hibernate知道什么是连接列,只要您将它映射到实体中,就不会在查询中告诉它。

答案 1 :(得分:0)

如果有人建议替代上述内容,我会将其标记为答案。由于情况并非如此,以下是解决子查询限制以及缺乏对“ON”关键字的支持的解决方法:

SELECT H, C
FROM HealthHistory H,
     NodeA A,
     NodeC C,
     NodeL L
WHERE A.someId = C.descendant.id -- A -> C
  AND A.something = someConstant
  AND C.someId = L.id -- C -> L
  AND C.something = someConstant
  AND L.something = someConstant
  AND H.someId = C.id -- H -> C
  AND H.something = someConstant
  AND H.someId = C.descendant.id
  AND H.insertion_time IN (
                       SELECT MAX(insertion_time)
                       FROM HealthHistory H2
                       WHERE H2.someId = C.descendant.id
  )