[英]How to query on inherited classes with querydsl
I use querydsl to query on a mongodb. 我使用querydsl在mongodb上查询。 As allowed by mongodb, in several cases I store objects of different types in the same collection.
正如mongodb所允许的,在某些情况下,我会将不同类型的对象存储在同一集合中。
For instance, in my data model I have: 例如,在我的数据模型中,我有:
interface Notification {
NotificationType getType(); // EMAIL, SMS etc.
}
interface EmailNotification extends Notification {
Set<User> getRecipients();
}
Now I want to query for Notifications of any kind (not only EmailNotification), but in the case I have EmailNotifications, I want to filter on some recipient. 现在,我想查询任何类型的通知(不仅是EmailNotification),但是如果我有EmailNotifications,我想对某些收件人进行过滤。
I tried this code (doesn't work): 我尝试了以下代码(无效):
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);
It doesn't throw any error or exception, but I don't get the expected result (actually I don't get any result) because the generated mongo query is wrong, and I can't get how to make it right. 它不会引发任何错误或异常,但是我没有得到预期的结果(实际上我没有任何结果),因为生成的mongo查询是错误的,而且我无法正确地做到这一点。
Generated query is like: 生成的查询就像:
{
"$and":[
// ...
{
"$or":[
{
"type":"EMAIL",
"notification.recipients.email":{
"$in":[
"a@b.com"
]
}
},
// ...
]
}
]
}
And the issue lies in the key "notification.recipients.email": it should be just "recipients.email". 问题出在关键“ notification.recipients.email”上:应该只是“ recipients.email”。
Why does "notification.as(QEmailNotification.class).recipients" translates to "notification.recipients", and how can I make it as expected ? 为什么“ notification.as(QEmailNotification.class).recipients”会转换为“ notification.recipients”,我该如何按预期进行呢?
Note that the following would work: 请注意,以下将起作用:
notificationPersister.query(EmailNotification.class).where(
QEmailNotification.eMailNotification.recipients.any().email.in(recipientEmails));
But then I'm forced to run 1 query per inherited class, which is not efficient. 但是然后我被迫对每个继承的类运行1个查询,这效率不高。
正如Timo所说:通过github.com/querydsl/querydsl/pull/1428在querydsl中修复
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.