在春季库接口的sort()和上限()查询(Query with sort() and limit()

2019-06-23 11:21发布

我是新来的MongoDB与春季数据,并希望有我的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();

    ...
}

我知道,一个可以为了得到排序添加一个排序参数的查询方法,但问题是限制的结果,只是一个单一的对象。 这是可能的,而无需编写自定义JobRepositoryImpl办?

谢谢

编辑:

什么我找实例:

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

要么

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

但是,这显然是行不通的:(

Answer 1:

出了什么问题:

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


Answer 2:

只要添加一个修正奥利弗的回答,这是Direction.DESC而不是Directions.DESC和则params的顺序是错误的。

更改:

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

至:

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


文章来源: Query with sort() and limit() in Spring Repository interface