繁体   English   中英

如何使用querydsl查询继承的类

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM