Would you please help me to create QueryDSL construct for SQL like below using JPA Query. I am using 4.1.3.
SELECT * FROM (SELECT a FROM b WHERE a.z = 1) WHERE rownum <=1;
The Solutions mentioned is not working for me QueryDSL - add subquery into FROM statement
Thanks in advance.
The below query:
SELECT a FROM b WHERE a.z = 1
does not have any
order by
clause, so default ordering will be applied. As per this SO answer, the ordering is not predicted. So, I recommend adding theorder by
clause.If this is just an example and the actual query contains
order by
then you can implement similar logic in a single query; rather than wrapping it into another query and get the first row, e.g. something like(SELECT a FROM b WHERE a.z = 1 order by z)
withrownum
. Below are the steps to do it via JPA way:PagingAndSortingRepository
as it already has some methods)findBy()
method that acceptsPageble
argument (along with z), it would look like this:public List<T> findByZ(int z, Pageable pageable)
Call it with
Z
andPageRequest
, e.g.:final PageRequest page1 = new PageRequest( 0, 1, Direction.ASC, "somefield" );
It would apply the
limit/rownnum
based on db you are using and give you the record(s).