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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With