我是Spring Data with MongoDB的新手,並希望在需要過濾,排序和限制的MongoRepository擴展接口中有一個自動生成的查詢方法。在Spring Repository接口中使用sort()和limit()進行查詢
查詢看起來是這樣的:
// '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();
但是,這顯然是行不通的:(
感謝奧利弗,這正是我一直在尋找。 – m1h4 2012-04-11 00:40:19
我忙於尋找一個簡短的查詢式解決方案,我並不打算檢查Pageable類,並意識到這與Sort排序相結合 - 包裝了.sort()和.limit()函數一個mongo查詢。 – m1h4 2012-04-11 07:34:07
沒問題,很高興爲你工作! :) – 2012-04-11 13:51:26