2012-04-21 78 views
0

我有三個班級:醫生,病人和諮詢。 Doctor和Patient類都有一個作爲字段的諮詢清單。如何在JPQL中編寫查詢?

@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; 
//... 
} 

我想從單個查詢中獲得醫生的患者;那就是所有與醫生諮詢相同的患者。請注意,Doctor和Patient之間沒有關係。 這是可行嗎?

select p from Patient p where p.consultations **someKeyword** (select d.consultations from Doctor d where d.id = :doctorId) 

如果我沒有記錯someKeyword包含是否會有

where list<entity> contains entity 

如果

where entity in list<entity> 

但在這種情況下,就是

list someKeyword list 

組合是:

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

但是這並做SENS?

我是JPA和JPQL的初學者。

+0

我找到了解決辦法;我從每次諮詢中獲得所有的諮詢和患者。不過,我想知道是否有什麼東西可以讓靈敏/可行。 – m3th0dman 2012-04-21 17:34:56

回答

2

喜歡的東西:

select p from Patient p 
where exists (
    select c from Consultation c 
    where c.patient = p 
    and c.doctor.id = :doctorId 
) 

+0

它以這種方式工作。謝謝! – m3th0dman 2012-04-22 09:43:57

0

可以中使用NamedQuery標註它看起來像下面

@NamedQuery(
    name = "findPatientForDoctor", 
    query = "SELECT c.patient FROM Consultation c WHERE c.doctor.id : id")) 

(只檢查獨此查詢的語法)

這將給予醫生ID一個病人。

由於您的關聯就像患者有諮詢,每個支持與患者和醫生有一對一的映射。目前,您的實體模型中沒有任何關係讓所有患者獲得醫生服務。病人與醫生是多對多的關係,目前你的實體似乎不支持這一點。我不認爲沒有病人醫生關係,你可以在一個單一的查詢中得到記錄。