Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to impose LIMIT on sub-query of JPA query?

Tags:

jpa

subquery

jpql

Is it possible to impose LIMIT on sub-query in JPA query ?

I have following query in pure SQL

select * from ipinfo 
where RangeEnd < (select RangeStart from ipinfo where RangeStart >= 1537022421 order by RangeStart asc limit 1) and (1537022421 <= RangeEnd)
ORDER BY RangeEnd desc
limit 1

Converting it directly to JPQL I'd have something like

select obj from IpInfo obj
where obj.rangeEnd < (select obj2.rangeStart from IpInfo obj2 where obj2.rangeStart >= ?1 order by obj2.rangeStart asc limit 1) and (?1 <= obj.rangeEnd)
ORDER BY obj.rangeEnd desc
limit 1

Since I can't use LIMIT in JPQL I'd have to use setMaxResults(1) on it. But what about sub-query?

Update:

I decided to go with @NamedNativeQuery for now but it's DB-specific code. If you guys can suggest pure JPA solution I'll really appreciate it.

like image 991
expert Avatar asked Dec 18 '11 22:12

expert


People also ask

How do I add a limit to a JPA query?

Spring Data JPA supports keywords 'first' or 'top' to limit the query results (e.g. findTopBy....). An optional numeric value can be appended after 'top' or 'first' to limit the maximum number of results to be returned (e.g. findTop3By....). If this number is not used then only one entity is returned.

Can we use subquery in JPQL?

A subselect is a query embedded into another query. It's a powerful feature you probably know from SQL. Unfortunately, JPQL supports it only in the WHERE clause and not in the SELECT or FROM clause. Subqueries can return one or multiple records and can use the aliases defined in the outer query.


1 Answers

It is not currently possible to add a LIMIT (maxResults) or OFFSET (startIndex) via JPQL, nor is it possible to do so on a JPA subquery. There is an open JPA ticket to add this functionality:

https://github.com/eclipse-ee4j/jpa-api/issues/88

like image 126
shelley Avatar answered Sep 16 '22 16:09

shelley