I have a three classes: Doctor, Patient and Consultation. Both Doctor and Patient classes have a list of consultations as field.
@Entity
public class Consultation {
@Id
@GeneratedValue
private int id;
private Calendar scheduleDate;
private String information;
private String symptoms;
@ManyToOne
private Doctor doctor;
@ManyToOne
private Patient patient;
//...
}
@Entity
public class Patient {
@Id
@GeneratedValue
private int id;
private String name;
private String ssn;
private String address;
@OneToMany(mappedBy = "patient")
private List<Consultation> consultations;
//...
}
@Entity
public class Doctor {
@Id
@GeneratedValue
private int id;
private String name;
private String specialization;
@OneToMany(mappedBy = "doctor")
private List<Consultation> consultations;
//...
}
I want to obtain the patients of a doctor from a single query; that is all the patients that have the same consultation as a doctor. Note that there is no connection between Doctor and Patient. Is this posible?
select p from Patient p where p.consultations **someKeyword** (select d.consultations from Doctor d where d.id = :doctorId)
If I'm not mistaken someKeyword would be contains if there would be
where list<entity> contains entity
and in if
where entity in list<entity>
but in this case there would be
list someKeyword list
A combination would be:
select p from Patient p where p.consultations contains (select c from Consultation c where c in (select d.consultations from Doctor d where d.id = :doctorId))
but does this make sens?
I am a beginner in JPA and JPQL.
Something like:
select p from Patient p
where exists (
select c from Consultation c
where c.patient = p
and c.doctor.id = :doctorId
)
?