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

18,102

Solution 1

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.

Solution 2

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

SELECT MAX(objDate) FROM Object
Share:
18,102

Related videos on Youtube

Abhishek
Author by

Abhishek

Geeky Java and Node Developer. Love movies and Technology.

Updated on June 04, 2022

Comments

  • Abhishek
    Abhishek almost 2 years

    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.

  • Abhishek
    Abhishek almost 13 years
    I was hoping not to use any named queries. By using Names query it is very simple but i was wondering if there was a way around this.
  • Abhishek
    Abhishek almost 13 years
    Thanks for the answer. I did actually find it. It returns a list but works just fine.
  • Brad Cupit
    Brad Cupit almost 12 years
    @Olver Gierke The only issue is it runs an unnecessary query to get the count. I just use QueryDSL in these cases, but a LimitOne syntax would be cool. Posted the suggestion here
  • norgence
    norgence almost 12 years
    It does not if you have a return type of List instead of Page.
  • Abhishek
    Abhishek over 10 years
    In Case of QueryDslJpaRepository there is only one method and it always runs a count query. Is there another workaround to this? @OliverGierke
  • Xegara
    Xegara almost 2 years
    How about the sort order ? QueryDslPredicateExecutor.findAll(Predicate predicate, Pageable pageable) does not include sort order.