Union in JPA query - from the same table

只谈情不闲聊 提交于 2019-12-01 21:06:13

问题


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'.

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

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'

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

Any other better suggestions welcome!


回答1:


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.

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

is viable solution.




回答2:


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.

See, http://java-persistence-performance.blogspot.com/2012/05/jpql-vs-sql-have-both-with-eclipselink.html



来源:https://stackoverflow.com/questions/17050589/union-in-jpa-query-from-the-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!