I'm new to Spring Data with MongoDB and would like to have an automagically generated query method inside my MongoRepository extension interface which requires filtering, sorting and limiting.
The query looks like this:
// 'created' is the field I need to sort against
find({state:'ACTIVE'}).sort({created:-1}).limit(1)
The repository interface looks like this:
public interface JobRepository extends MongoRepository<Job, String> {
@Query("{ state: 'ACTIVE', userId: ?0 }")
List<Job> findActiveByUserId(String userId);
// The next line is the problem, it wont work since
// it's not in the format @Query expects
@Query("find({state:'ACTIVE'}).sort({created:-1}).limit(1)")
Job findOneActiveOldest();
...
}
I know that one can add a Sort argument to a query method in order to get sorting but the problem is limiting the results to just a single object. Is this possible to do without having to write a custom JobRepositoryImpl?
Thanks
Edit:
Example of what I am looking for:
@Query("{ state:'ACTIVE', $orderby: {created:-1}, $limit:1 }")
Job findOneActiveOldest();
or
@Query("{ state:'ACTIVE' }")
@Sort("{ created:-1 }")
@Limit(1)
Job findOneActiveOldest();
But this obviously doesn't work :(
JPA Setup In our repository method, we use the EntityManager to create a Query on which we call the setMaxResults() method. This call to Query#setMaxResults will eventually result in the limit statement appended to the generated SQL: select passenger0_.id as id1_15_, passenger0_.
Spring Data JPA allows you to add a special Sort parameter to your query method. The Sort class is just a specification that provides sorting options for database queries. By using dynamic sorting, you can choose the sorting column and direction at runtime to sort the query results.
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.
What's wrong with:
public interface JobRepository extends MongoRepository<Job, String> {
@Query("{ state : 'ACTIVE' }")
Page<Job> findOneActiveOldest(Pageable pageable);
}
and using it:
// Keep that in a constant if it stays the same
PageRequest request = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "created"));
Job job = repository.findOneActiveOldest(request).getContent().get(0);
Just adding a correction to Oliver's answer, it's Direction.DESC
and not Directions.DESC
and the order of the params is wrong.
Change :
PageRequest request = new PageRequest(0, 1, new Sort("created", Directions.DESC));
to:
PageRequest request = new PageRequest(0, 1, new Sort(Direction.DESC, "created"));
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