在Spring Repository接口中使用sort()和limit()进行查询

时间:2012-04-08 22:45:26

标签: spring-data mongodb-java

我是使用MongoDB的Spring Data的新手,我希望在MongoRepository扩展接口中有一个自动生成的查询方法,需要过滤,排序和限制。

查询如下所示:

// 'created' is the field I need to sort against

find({state:'ACTIVE'}).sort({created:-1}).limit(1)

存储库界面如下所示:

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

    ...
}

我知道可以在查询方法中添加Sort参数以便进行排序,但问题是将结果限制为单个对象。这可以在不必编写自定义JobRepositoryImpl的情况下完成吗?

由于

编辑:

我正在寻找的例子:

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

@Query("{ state:'ACTIVE' }")
@Sort("{ created:-1 }")
@Limit(1)
Job findOneActiveOldest();

但这显然不起作用:(

2 个答案:

答案 0 :(得分:34)

出了什么问题:

public interface JobRepository extends MongoRepository<Job, String> {

  @Query("{ state : 'ACTIVE' }")
  Page<Job> findOneActiveOldest(Pageable pageable);
}

并使用它:

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

答案 1 :(得分:9)

只需在Oliver的答案中添加更正,它是Direction.DESC而不是Directions.DESC,并且参数的顺序是错误的。

更改:

PageRequest request = new PageRequest(0, 1, new Sort("created", Directions.DESC));

为:

PageRequest request = new PageRequest(0, 1, new Sort(Direction.DESC, "created"));