Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use order by and Limit in Spring Data JPA using QueryDSL

I am using Spring Data JPA with a RDBMS in my project. I have a requirement where I have to fetch a single record from the Database from a table which has the latest date. For this I need to use a limit and order by function OR using sub queries. However, I wished to know if i wish for not to use NamedQuery is there a way I can achieve this using Spring Data JPA and QueryDSL.

like image 378
Abhishek Avatar asked Jun 15 '11 10:06

Abhishek


People also ask

How do I limit query results in Spring data JPA?

Limiting query results in JPA is slightly different to SQL; we don't include the limit keyword directly into our JPQL. Instead, we just make a single method call to Query#maxResults, or include the keyword first or top in our Spring Data JPA method name. As always, the code is available over on GitHub.

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.

Does JPQL support limit?

As stated in the comments, JPQL does not support the LIMIT keyword. You can achieve that using the setMaxResults but if what you want is just a single item, then use the getSingleResult - it throws an exception if no item is found.

What is QueryDSL in spring?

Querydsl is an extensive Java framework, which allows for the generation of type-safe queries in a syntax similar to SQL. It currently has a wide range of support for various backends through the use of separate modules including JPA, JDO, SQL, Java collections, RDF, Lucene, Hibernate Search, and MongoDB.


2 Answers

Shouldn't QueryDslPredicateExecutor.findAll(Predicate predicate, Pageable pageable) do the trick for you? You could hand in a new PageRequest(0, limit) and thus would get back the first limitresults.

like image 96
Oliver Drotbohm Avatar answered Oct 04 '22 16:10

Oliver Drotbohm


How about using the MIN and MAX function to attain this.

SELECT MAX(objDate) FROM Object
like image 42
Talha Ahmed Khan Avatar answered Oct 04 '22 17:10

Talha Ahmed Khan