[英]How to query on inherited classes with querydsl
我使用querydsl在mongodb上查詢。 正如mongodb所允許的,在某些情況下,我會將不同類型的對象存儲在同一集合中。
例如,在我的數據模型中,我有:
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":[
"a@b.com"
]
}
},
// ...
]
}
]
}
問題出在關鍵“ 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個查詢,這效率不高。
正如Timo所說:通過github.com/querydsl/querydsl/pull/1428在querydsl中修復
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.