@Entity
public class doctor {
@Id
private int id;
private String username;
private String password;
private String phone;
private String email;
@OneToMany(targetEntity = patient.class, cascade = CascadeType.ALL, mappedBy = "doctor")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Collection<patient> patients = new ArrayList<patient>();
}
@Entity
public class patient {
@Id
private int id;
private String name;
private String surname;
private String phone;
private int systolic;
private int diastolic;
@ManyToOne
private doctor doctor;
}
目前我只能通过以下标准检索医生信息:
Criteria query = session.createCriteria(doctor.class);
query.createCriteria("patients", "p");
query.add(Restrictions.eq("p.phone", phone));
List<doctor> doctorList = (ArrayList<doctor>) query.list();
通过提供患者电话,医生信息和一些患者信息,如何通过hibernate标准进行检索?
类似于:phone = 3423423424,然后是answear:
-------------医生的信息-------------------------------- --patientinfo(收缩压,舒张压)-----------------------
1 "Dr dre" sdfssd 243242 drdre@gmail.com 160 170
其中160 170
是患者的信息
如果没有标准,使用HQL?
答案 0 :(得分:2)
您想要的是以下内容。
使用Hibernate Criteria API:
Criteria query = sessionFactory.getCurrentSession().
createCriteria(Patient.class, "patient");
query.setProjection(Projections.projectionList().
add(Projections.property("patient.doctor")).
add(Projections.property("patient.systolic")).
add(Projections.property("patient.diastolic")));
query.add(Restrictions.eq("patient.phone", phone));
return query.list();
使用HQL(实际上只是JPQL):
select p.doctor, p.systolic, p.diastolic from Patient p where p.phone = ?1
您在结果中获得的是类型List<Object[]>
的值。
同时在@Cascade(value=CascadeType.SAVE_UPDATE)
课程中将doctor
添加到Patient
字段。
答案 1 :(得分:1)
您的查询仅返回医生信息(而不是患者信息)的原因是因为for a OneToMany relation, FetchType by default is set to LAZY,如果您将获取类型指定为EAGER,则hibernate也将返回患者。
@OneToMany(targetEntity = patient.class, cascade = CascadeType.ALL, mappedBy = "doctor", fetch = FetchType.EAGER)
答案 2 :(得分:1)
您有双向映射,因此每位医生都可以得到患者,每位患者都可以获得医生信息。如果您需要患者列表而不是医生列表,只需为患者创建类似的标准。 session.createCriteria(patient.class)
,需要限制。你不必急于求成。在大多数情况下,我们不需要急切的提取。如果你需要hibernate会话之外的对象,那么初始化(Hibernate.initialize)集合或代理要好得多。
btw在命名java类时使用camel case。它被广泛使用的惯例。
答案 3 :(得分:1)
如果您使用的是HibernateTemplate
String hql = "from Boo where id in (:listParam)";
String[] params = { "listParam" };
Object[] values = { list};
List boos = getHibernateTemplate().findByNamedParam(hql, params, values);