Query with sort() and limit() in Spring Repository interface

落爺英雄遲暮 提交于 2019-12-17 15:42:51

问题


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 :(


回答1:


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);



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!