14

I was looking to see how I could introduce a sort into a Query annotation in a repository method that I have. I already saw this code in Google and here, but I could not make it works

@Query("find({state:'ACTIVE'}).sort({created:-1}).limit(1)")
    Job findOneActiveOldest();

@Query("{ state:'ACTIVE', $orderby: {created:-1}, $limit:1 }")
Job findOneActiveOldest();

I know that with pagination I can make it, but in some cases I don't need paginate, so I was wondering how to make it with Query annotation.

Any suggestion please?

Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
paul
  • 12,873
  • 23
  • 91
  • 153

3 Answers3

25

I don't think it is possible to do it with @Query annotation. If you dont need to paginate you can just make your repository method use Sort parameter:

@Query("{ state:'ACTIVE' }")
Job findOneActive(Sort sort);

and use it:

yourRepository.findOneActive(new Sort(Sort.Direction.DESC, "created"))
Maciej Walkowiak
  • 12,372
  • 59
  • 63
16

Just use sort parameter of @Query annotation. 1 = ASC, -1 = DESC

    @Query(
        value  = ...,
        sort = "{'details.requestTime': -1}"
    )
lukyer
  • 7,595
  • 3
  • 37
  • 31
0

if you also want to have pagination then use Pageable as method argument instead of Sort. Try below code:

@Query("{ state:'ACTIVE' }")
Job findOneActive(Pageable pageable);

yourRepository.findOneActive(new PageRequest(0, 1, new Sort(Sort.Direction.DESC,"created")));
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51