我有两个Java实体,我建立了多对多的双向关系。我正在使用JBOSS服务器和hibernate注释映射。
患者实体
@Entity
@Table(name = "patient")
public class Patient implements Serializable {
...
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "treats", joinColumns = { @JoinColumn(name = "patient_id") },
inverseJoinColumns = { @JoinColumn(name = "doctor_id") })
private List<Doctor> doctors = new ArrayList<Doctor>();
医生实体
@Entity
@Table(name = "doctor")
public class Doctor implements Serializable {
...
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "doctors")
private List<Patient> patients = new ArrayList<Patient>();
我想查询添加到患者身上的医生。如何使用HQL来解决这个问题?我也需要设置参数。 我试过这个方法(它在DAO类中):
public List<Doctor> getDoctorsForPatient(Patient patient) {
StringBuilder query = new StringBuilder();
query.append("from Patient doctors ");
query.append("inner join Patient where patient in :patient");
return getSession().createQuery(query.toString())
.setParameter("patient", patient)
.list();
}
我也试过从'treats'(n:m关联表)表中查询,但我有一个例外,它没有映射。