JPA查询中的联合-来自同一表 [英] Union in JPA query - from the same table

查看:128
本文介绍了JPA查询中的联合-来自同一表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,我需要限制从表返回的特定标志的记录数,以及所有记录的另一个标志值的数.

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.

例如:contact-history表中有一个名为IorM_flg的元素,可能的值为'm'和'o'.

For example: contact-history table has an element called IorM_flg with possible values 'm' and 'o'.

我只需要返回10条'o'记录和所有'm'条记录.

I need to return only 10 records of 'o' and all records of 'm'.

我正要为此用union编写查询.像这样:

I was about to write a query with union for this. Something like this:

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'

这可能吗? 请注意,它是一个JPA查询. (contact_history是对象名称)

Is this possible? Note that its a JPA query. (contact_history is object name)

欢迎其他更好的建议!

推荐答案

否,这对于JPQL是不可能的,因为它没有UNION(ALL).另外,没有办法用rownum限制查询字符串本身返回的行数,但这是通过

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.

在许多情况下

  • 执行两个查询,
  • 使用setMaxResults限制第一个结果的数量,并且
  • 在Java中丢弃重复项并合并两个查询的结果

是可行的解决方案.

这篇关于JPA查询中的联合-来自同一表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆