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.
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.
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.
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.
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.
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 limit
results.
How about using the MIN and MAX function to attain this.
SELECT MAX(objDate) FROM Object
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