2013-10-25 46 views
0

我無法根據嵌入式Java集合的字段值查詢MongoDB文檔。如何在Java集合的元素屬性的子集上構建Morphia查詢?

我有以下實體:

@Entity 
public class StationHistoryEntry // extends ... 
{ 
    @Embedded 
    private Set<SongFeedback> songFeedback = new HashSet<SongFeedback>(); 

    // ... 
} 

而下面嵌入類:

@Embedded 
public class SongFeedback // extends ... 
{ 
    @Embedded 
    private FeedbackType feedbackType; 

    private ObjectId userId; 

    public enum FeedbackType { 
     THUMBS_UP, THUMBS_DOWN, STAR; 
    } 

    // other properties 
} 

我需要做的是找到StationHistoryEntriesSongFeedback與給定userIdfeedbackType=STAR

我試過以下,但是當其他SongFeedback特性(在代碼片段沒有顯示,因爲我沒有對他們的價值觀控制的那些)沒有null,這發生在生產沒有成功:

public List<StationHistoryEntry> findStarredByUserId(ObjectId userId) { 
    SongFeedback songFeedback = new SongFeedback(FeedbackType.STAR, userId); 
    return ds.find(StationHistoryEntry.class) 
     .filter("songFeedback elem", songFeedback).asList(); 
} 

而且我也試過以下,但它總是返回一個空列表:如果有幫助的一切,我已經創建與剝離下來的代碼和一個Github上庫

public List<StationHistoryEntry> findStarredByUserId(ObjectId userId) { 
    Query<StationHistoryEntry> query = ds.createQuery(StationHistoryEntry.class); 
    query.and(
     query.criteria("songFeedback.userId").equal(userId), 
     query.criteria("songFeedback.feedbackType").equal(FeedbackType.STAR)); 
    return query.asList(); 
} 

單元測試:https://github.com/gabrielcs/MorphiaQueryStackOverflow

任何想法?謝謝!

回答

0

試試這個

public List<StationHistoryEntry> findStarredByUserId(ObjectId userId) { 
    Query<StationHistoryEntry> query = ds.createQuery(StationHistoryEntry.class); 
    query.and(
     query.criteria("songFeedback.userId").equal(userId), 
     query.criteria("songFeedback.feedbackType").in(FeedbackType.STAR)); 
    return query.asList(); 
} 
+0

感謝您的反饋,但因爲'在()'預計的'Iterable'我有一個編譯錯誤。如果它有幫助,我創建了一個Github存儲庫,其中包含精簡代碼和一個單元測試:https://github.com/gabrielcs/MorphiaQueryStackOverflow –

+0

您可以將它包裝在List中:Arrays.asList(FeedbackType.STAR ) – evanchooly

+0

沒有更多的編譯錯誤。但是,如果我通過'userId1'查詢已加星標的歌曲,並且'userId1'帶有'THUMBS_UP SongFeedback'和'userId2'帶有'STAR SongFeedback'的'StationHistoryEntry s',會發生什麼情況,結果將包含''',這不應該發生。我在查詢結果中需要的'findStarredByUserId(userId1)'僅僅是'StationHistoryEntries',它至少有一個帶有'userId1'和'STAR'的單一的SongFeedback。 –

相關問題