Search code examples
javahibernatehqlhibernate-criteria

How to inner join two tables using Hibernate HQL or Criteria?


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

For now i can retreive only doctors information by this criteria:

Criteria query = session.createCriteria(doctor.class);
query.createCriteria("patients", "p");
query.add(Restrictions.eq("p.phone", phone));
List<doctor> doctorList = (ArrayList<doctor>) query.list();

How i can with hibernate criteria retreive by giving patient phone, his doctor information and some patients information?

Something like : phone=3423423424 , then answear is :

-------------doctor's info----------------------------------patientinfo(systolic,diastolic)-----------------------

  1 "Dr dre" sdfssd 243242 [email protected]  160 170

where 160 170 are the patient's information

If not with criteria, with HQL?


Solution

  • You have bidirectional mapping so from each doctor you can get his patients and from each patient you can get his doctor information. If you need a list with patients instead a list of doctors just create analogous Criteria for patients. session.createCriteria(patient.class), with needed restrictions. you don't have to make it eager. In most cases we don't need eager fetching. It is much better initialize (Hibernate.initialize) the collection or proxy if you would need the objects outside the hibernate session.

    btw use camel case when you name java classes. It's widely used convention.