I have a noticication entity that has OneToMany relationship with its parameters, which is a list of NotificationParamEntity objects.
The code for both classes looks like:
// 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;
......
}
Now I can use the query below to get the notification that has a parameter named “P1” and with a value “V1”:
SELECT DISTINCT anEntity FROM NotificationEntity anEntity, IN
(anEntity.params) p WHERE p.key = “P1” AND p.value = ‘V1’
But when I want to find out the notification that has two specified parameters(P1=V1 and P2=V2), my query below failed to find anything:
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”
I can understand why it doesn’t work: there is no parameter that can have two different keys, so the query return nothing.
But how to make this work? Assume I have a notification entity that has two parameters, one is named P1 and value is V1, the other one is P2 and the value is V2, how can I find this notification entity with JPQL query?
Try something like this:
Note that it requires a reference from NotificationParamEntity to NotificationEntity (I don’t see that column in the snippet of your code, but you should have it, a @ManyToOne).