2015-07-02 44 views
1

我使用querydsl在mongodb上查詢。正如mongodb所允許的,在幾種情況下,我將不同類型的對象存儲在同一個集合中。如何使用querydsl查詢繼承類

舉例來說,在我的數據模型,我有:

interface Notification { 
    NotificationType getType(); // EMAIL, SMS etc. 
} 

interface EmailNotification extends Notification { 
    Set<User> getRecipients(); 
} 

現在我想要查詢任何類型的(不僅EmailNotification)的通知,但我有EmailNotifications的情況下,我要過濾一些收件人。

我想這個代碼(不工作):

final QNotification notification = QNotification.notification; 
final BooleanBuilder typesPredicate = new BooleanBuilder(); 
// "recipientEmails" and "recipientPhones" are provided parameters (lists of String) 
typesPredicate.or(notification.type.eq(NotificationType.EMAIL) 
        .and(notification.as(QEmailNotification.class).recipients 
         .any().email.in(recipientEmails))); 

typesPredicate.or(notification.type.eq(NotificationType.SMS) 
        .and(notification.as(QSMSNotification.class).recipients 
         .any().phoneNumber.in(recipientPhones))); 


notificationPersister.query(Notification.class).where(typesPredicate); 

它不會引發任何錯誤或異常,但我沒有得到期望的結果(其實我沒有得到任何結果),因爲生成的mongo查詢是錯誤的,我不知道如何使它正確。

生成的查詢是這樣的:

{ 
    "$and":[ 
     // ... 
     { 
    "$or":[ 
     { 
      "type":"EMAIL", 
      "notification.recipients.email":{ 
       "$in":[ 
       "[email protected]" 
       ] 
      } 
     }, 
      // ... 
    ] 
     } 
    ] 
} 

而問題在於關鍵 「notification.recipients.email」:它應該只是 「recipients.email」。

爲什麼「notification.as(QEmailNotification.class).recipients」轉換爲「notification.recipients」,我該如何按預期做到?

請注意,以下將工作:

notificationPersister.query(EmailNotification.class).where(
    QEmailNotification.eMailNotification.recipients.any().email.in(recipientEmails)); 

但後來我不得不每運行繼承類1個查詢,效率不高。

+0

PS在querydsl修正:又見https://groups.google.com/forum/#!topic/querydsl/KaUWIUwov6w – Joel

+0

通過https://github.com/querydsl/querydsl/pull/1428修復 –

回答

0

正如蒂莫說:通過github.com/querydsl/querydsl/pull/1428