【问题标题】:How to write JPQL query using multiple members of same collection?如何使用同一集合的多个成员编写 JPQL 查询?
【发布时间】:2012-07-23 22:02:03
【问题描述】:

我有一个通知实体,它与其参数具有 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 查询找到该通知实体?

【问题讨论】:

    标签: jpa collections jpql one-to-many


    【解决方案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 的引用(我在您的代码的 sn-p 中没有看到该列,但您应该拥有它,@ManyToOne)。

    【讨论】:

    • 谢谢,使用子查询可以解决问题。你是对的,NotificationParamEntity 引用了 NotificationEntity,我只是编辑问题并添加它。
    猜你喜欢
    • 1970-01-01
    • 2011-02-20
    • 2011-09-26
    • 2014-05-04
    • 2012-05-02
    • 2011-11-09
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多