2012-04-08 178 views
11

我是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(); 

但是,這顯然是行不通的:(

回答

24

什麼是與NG:

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

感謝奧利弗,這正是我一直在尋找。 – m1h4 2012-04-11 00:40:19

+2

我忙於尋找一個簡短的查詢式解決方案,我並不打算檢查Pageable類,並意識到這與Sort排序相結合 - 包裝了.sort()和.limit()函數一個mongo查詢。 – m1h4 2012-04-11 07:34:07

+0

沒問題,很高興爲你工作! :) – 2012-04-11 13:51:26

7

只要添加一個修正奧利弗的回答,這是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")); 
+7

這應該是一個評論,而不是一個答案。 – 2014-07-30 14:32:38

+0

或編輯原始答案,但現在我想到了,新用戶沒有編輯評論或編輯。 – shoover 2014-07-30 14:35:42

+0

@Sinatr在meta上看到[this discussion](http://meta.stackoverflow.com/questions/260245/when-should-i-make-edits-to-code),特別是「編輯代碼在答案」部分。 TL; DR:SO是參考資源,而不是遊戲;如果產生改進,編輯會受到鼓勵;所有編輯都會記錄下來,任何人都可以查看歷史記錄 – shoover 2014-07-30 16:40:36

相關問題