from 子句中的 JPA/hibernate 子查询
Posted
技术标签:
【中文标题】from 子句中的 JPA/hibernate 子查询【英文标题】:JPA/hibernate subquery in from clause 【发布时间】:2011-11-08 07:12:39 【问题描述】:我们使用 JPA 和 hibernate 作为提供者, 我们有一个查询,它在 FROM 子句中包含一个带有子查询的连接,但我们收到以下错误:
org.hibernate.hql.ast.QuerySyntaxException:意外令牌:(附近 第 1 行,第 75 列 [SELECT sd FROM com.hp.amber.datamodel.entities.analysis.SnapshotDates sd,(选择 max(x.changeDate) maxChangeDate, x.viewId, x.state FROM com.hp.amber.datamodel.entities.analysis.SnapshotDates x WHERE x.changeDate<:date and x.viewid in x.state=":state" group sd2 sd.viewid="sd2.viewId" sd.state=":state" sd.changedate="sd2.maxChangeDate]</p">
这是查询:
SELECT sd
FROM SnapshotDates sd,
(SELECT max(x.changeDate) maxChangeDate, x.viewId, x.state
FROM SnapshotDates x
WHERE x.changeDate<:date AND x.viewId in (:viewIds) AND x.state=:state
GROUP BY x.viewId, x.state) sd2
WHERE sd.viewId = sd2.viewId
AND sd.state = :state
AND sd.changeDate = sd2.maxChangeDate
感谢您的帮助
【问题讨论】:
jpa 不支持“FROM”和“SELECT”子句中的子查询,您必须更改查询并将子查询放在“WHERE”子句中。 【参考方案1】:我不认为 HQL 可以在 from 子句中做子查询
https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch16.html#queryhql-subqueries
注意句子:
请注意,HQL 子查询只能出现在 select 或 where 子句中。
我想您可以将其更改为本机查询并以这种方式执行。
【讨论】:
【参考方案2】:你的 SQL 是:
从 SnapshotDates sd 中选择 sd, (SELECT max(x.changeDate) maxChangeDate, x.viewId, x.state FROM SnapshotDates x WHERE x.changeDate<:date and x.viewid in x.state=":state" group by sd2 where sd.viewid="sd2.viewId" sd.state=":state" sd.changedate="sd2.maxChangeDate</p">
你可以像这样重写你的sql
SELECT sd
FROM SnapshotDates sd,
WHERE sd.viewId in (:viewIds)
AND sd.state = :state
sd.changeDate = (SELECT max(x.changeDate) FROM SnapshotDates x WHERE x.viewId = ds.viewId AND x.state = ds.state)
从示例中寻找灵感
SELECT m FROM Professor m WHERE (SELECT COUNT(e) FROM Professor e WHERE e.manager = m) > 0
http://www.java2s.com/Code/Java/JPA/EJBQLWhereClauseWithSubQuery.htm
我的类似例子 我有 SQL
select k.* from kredits k,
(select client_id, max(r_date) r_date from kredits k group by client_id) k2
where k.client_id = k2.client_id
AND k.r_date = k2.r_date
order by k.id
为 PQL 重写它
select k From Kredit k
where k.rDate = (select MAX(k2.rDate) from Kredit k2 where k2.clientId = k.clientId)
order by k.id
会被翻译成
select kredit0_.id as id28_, kredit0_.client_id as client59_28_ from kredits kredit0_
where kredit0_.r_date=(select MAX(kredit1_.r_date) from kredits kredit1_ where kredit1_.client_id=kredit0_.client_id)
order by kredit0_.id
返回与 SQL 相同的结果。
将 Hebirnate 3.3.1 与 mysql 5.0.24 一起使用
【讨论】:
请帮我翻译查询:select t.order_state,t.claim_number,t.id from (select * from t_repair_order where claim_number='SERCON201465') t where t.order_state = 'Cancel' and not exists ( select 1 from (select * from t_repair_order where claim_number='SERCON201465') tt where tt.id > t.id and tt.order_state <> t.order_state );
以上是关于from 子句中的 JPA/hibernate 子查询的主要内容,如果未能解决你的问题,请参考以下文章
无法在 FROM 子句中使用子查询编写 JPQL 查询 - Spring Data Jpa - Hibernate