2012-07-25 33 views
0

我有一个与它的参数具有OneToMany关系的通知实体,它是一个NotificationParamEntity对象的列表。如何使用同一集合的多个成员编写JPQL查询?

两个类的代码如下所示:

// 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其中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查询找到此通知实体?

回答

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 )。

+0

谢谢,使用子查询可以做到这一点。你是对的,NotificationParamEntity具有对NotificationEntity的引用,我只是编辑问题并添加它。 – Yun 2012-07-25 14:54:16