0

我有一个通知实体,它与其参数具有 OneToMany 关系,它是 NotificationParamEntity 对象的列表。

这两个类的代码如下所示:

// Notification Entity
@Entity
@Table (name = "NOTIFICATIONS")
public class NotificationEntity {
    ......
    @OneToMany (mappedBy = "notification")
    private List<NotificationParamEntity> params;
    ......
}

// Notification Parameter Entity
@Entity
@Table (name = "NOTIFICATIONS_PARAM")
public class NotificationParamEntity {
    ......
    @Column (name = "KEY", length = 40, nullable = false)
    @Enumerated (EnumType.STRING)
    private NotificationParameterEnum key;

    @Column (name = "VALUE", length = 4000, nullable = false)
    private String value;

    @ManyToOne
    @JoinColumn (name = "NOTIFICATION_ID", nullable = false)
    private NotificationEntity notification;
    ......
}

现在我可以使用下面的查询来获取具有名为“P1”的参数和值为“V1”的通知:

SELECT DISTINCT anEntity FROM NotificationEntity anEntity, IN (anEntity.params) p WHERE p.key = "P1" AND p.value = 'V1'

但是当我想找出具有两个指定参数(P1=V1 和 P2=V2)的通知时,我在下面的查询找不到任何东西:

SELECT DISTINCT anEntity FROM NotificationEntity anEntity, IN (anEntity.params) p WHERE p.key = "P1" AND p.value = 'V1' AND p.key = "P2" AND p.value = "V2"

我可以理解为什么它不起作用:没有参数可以有两个不同的键,所以查询什么也不返回。

但是如何使这项工作?假设我有一个通知实体,它有两个参数,一个名为 P1,值为 V1,另一个为 P2,值为 V2,如何使用 JPQL 查询找到此通知实体?

4

1 回答 1

1

尝试这样的事情:

SELECT n FROM NotificationEntity n WHERE EXISTS 
     (SELECT p FROM NotificationParamEntity p WHERE p.key = 'P1' AND p.value = 'V1' 
     AND p.notificationEntity = n) 
AND EXISTS 
     (SELECT p2 FROM NotificationParamEntity p2 WHERE p2.key = 'P2' AND p2.value = 'V2' 
     AND p2.notificationEntity = n)

请注意,它需要从 NotificationParamEntity 到 NotificationEntity 的引用(我在您的代码片段中没有看到该列,但您应该拥有它,@ManyToOne)。

于 2012-07-25T13:41:40.090 回答