在 Spring Repository 接口中使用 sort() 和 limit() 进行查询 [英] Query with sort() and limit() in Spring Repository interface

查看:26
本文介绍了在 Spring Repository 接口中使用 sort() 和 limit() 进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

查询如下所示:

// '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 是否可以做到这一点?

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?

谢谢

我正在寻找的示例:

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

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

但这显然行不通:(

推荐答案

有什么问题:

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

这篇关于在 Spring Repository 接口中使用 sort() 和 limit() 进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆