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 :(
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"));
来源:https://stackoverflow.com/questions/10067169/query-with-sort-and-limit-in-spring-repository-interface