在Spring Repository接口中使用sort()和limit()查询 [英] Query with sort() and limit() in Spring Repository interface
本文介绍了在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屋!
查看全文