如何在 JPA 2.0、Criteria API 中使用 In-Expressions 编写子查询?
我曾多次尝试编写带有子查询和 IN 表达式的查询语句,但从未成功。
我总是收到异常“关键字‘IN’附近的语法错误”。查询语句是这样构建的,
SELECT t0.ID, t0.NAME
FROM EMPLOYEE t0
WHERE IN (SELECT ?
FROM PROJECT t2, EMPLOYEE t1
WHERE ((t2.NAME = ?) AND (t1.ID = t2.project)))
我知道 IN
之前的单词丢失了。
你写过这样的查询吗?有什么建议吗?
I have tried to write a query statement with a subquery and an IN
expression for many times, but I have never succeeded.
I always get the exception, "Syntax error near keyword 'IN'". The query statement was build like this,
SELECT t0.ID, t0.NAME
FROM EMPLOYEE t0
WHERE IN (SELECT ?
FROM PROJECT t2, EMPLOYEE t1
WHERE ((t2.NAME = ?) AND (t1.ID = t2.project)))
I know the word before IN
is missing.
Have you ever written such a query? Any suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
下面是使用 Criteria API 使用子查询的伪代码。
此外,它肯定需要一些修改,因为我已尝试根据您的查询来映射它。这是一个链接 http://www.ibm.com/developerworks/java/library/j-typesafejpa / 这很好地解释了概念。
Below is the pseudo-code for using sub-query using Criteria API.
Also it definitely needs some modification as I have tried to map it according to your query. Here is a link http://www.ibm.com/developerworks/java/library/j-typesafejpa/ which explains concept nicely.
迟来的复活。
您的查询似乎与本书第 259 页的查询非常相似 Pro JPA 2:
Mastering the Java Persistence API,在 JPQL 中显示为:
使用 EclipseLink + H2 数据库,我无法使本书的 JPQL 或相应的标准正常工作。对于这个特定问题,我发现如果您直接引用 id,而不是让持久性提供程序弄清楚一切都按预期工作:
最后,为了解决您的问题,这里有一个等效的强类型标准查询,可以工作:
Late resurrection.
Your query seems very similar to the one at page 259 of the book Pro JPA 2:
Mastering the Java Persistence API, which in JPQL reads:
Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:
Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:
如果表
A
B
仅通过表AB
连接,则可以使用双连接。这只是另一种选择
很抱歉这个时机,但我遇到了这个问题,我也想做
SELECT IN
但我什至没有想到双重连接。我希望它能帮助某人。
You can use double join, if table
A
B
are connected only by tableAB
.That's just an another option
Sorry for that timing but I have came across this question and I also wanted to make
SELECT IN
but I didn't even thought about double join.I hope it will help someone.