我是 Spring Data with 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();
...
}
我知道可以将 Sort 参数添加到查询方法中以便进行排序,但问题是将结果限制为单个对象。这是否可以在无需编写自定义 JobRepositoryImpl 的情况下完成?
Thanks
Edit:
我正在寻找的示例:
@Query("{ state:'ACTIVE', $orderby: {created:-1}, $limit:1 }")
Job findOneActiveOldest();
or
@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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)