java JPA 查询中的联合 - 来自同一个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17050589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Union in JPA query - from the same table
提问by Kevin Rave
I have a requirement where I need to restrict number of records returned from a table for a particular flag and all records for the other flag value.
我有一个要求,我需要限制从表返回的特定标志的记录数和其他标志值的所有记录。
For example: contact-history
table has an element called IorM_flg
with possible values 'm' and 'o'.
例如:contact-history
table 有一个元素IorM_flg
,其可能的值是 'm' 和 'o'。
I need to return only 10 records of 'o' and all records of 'm'.
我只需要返回“o”的 10 条记录和“m”的所有记录。
I was about to write a query with union for this. Something like this:
我正要为此编写一个带有 union 的查询。像这样的东西:
select ch from contact_history where ch.rownum <= 10 and ch.IorM_flg = 'o'
Union All
select ch from contact_history where ch.IorM_flg != 'o'
Is this possible? Note that its a JPA query. (contact_history is object name)
这可能吗?请注意,它是一个 JPA 查询。(contact_history 是对象名称)
Any other better suggestions welcome!
欢迎大家有其他更好的建议!
采纳答案by Mikko Maunu
No, this is not possible with JPQL, because it does not have UNION (ALL). Additionally there is no way to limit amount of rows returned in query string itself with rownum, but that is done via setMaxResults.
不,这在 JPQL 中是不可能的,因为它没有 UNION (ALL)。此外,无法使用 rownum 限制查询字符串本身返回的行数,但这是通过setMaxResults完成的。
In many situations
在很多情况下
- executing two queries,
- limiting number of results in first one with setMaxResults, and
- discarding duplicates and combining results of both queries in Java
- 执行两个查询,
- 使用 setMaxResults 限制第一个结果的数量,以及
- 在 Java 中丢弃重复项并合并两个查询的结果
is viable solution.
是可行的解决方案。
回答by James
JPA does not support UNION, but if you use EclipseLink, UNION is supported in JPQL. Also the COLUMN operator can be used to access special columns like rownum.
JPA 不支持 UNION,但如果您使用 EclipseLink,则 JPQL 支持 UNION。此外,COLUMN 运算符可用于访问特殊列,如 rownum。
See, http://java-persistence-performance.blogspot.com/2012/05/jpql-vs-sql-have-both-with-eclipselink.html
见, http://java-persistence-performance.blogspot.com/2012/05/jpql-vs-sql-have-both-with-eclipselink.html