Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate inner join using hql

I am new to Hibernate. I have two tables, e.g., student and phone number and these two tables have a common column, student id. I want to do an inner join with these two tables using Hibernate hql.

student.java

{
   private int id;   
   private String name;   
}

phone.java

{
   private int pid;
   private int sid;  //same id in student.java 
   private int phone_number;
}
like image 657
Livin As Avatar asked Sep 13 '12 10:09

Livin As


2 Answers

Read the documentation again. You're not supposed to have the ID of the student in the Phone entity. Rather, you're supposed to have an association between both entities: a Phone belongs to a Student:

public class Phone {
    @Id
    private Integer id;

    private String phoneNumber;

    @ManyToOne
    private Student owner;
}

Only then will you be able to use joins:

// selects all the phones belonging to the students named 'John'
select phone from Phone phone where phone.owner.name = 'John'
like image 125
JB Nizet Avatar answered Sep 21 '22 16:09

JB Nizet


With the two classes like that hibernate is unaware of the association that makes life difficult. What would be normal is to make the sid in the phone class an actual Student object so hibernate is aware of the association. e.g.

class Phone {
    @ManyToOne
    @Column(name = "sid")
    private Student student;
}

having done this then you can do a simple HQL join e.g.

FROM Phone p
JOIN p.student s

Alternatively if there is some reason you want the raw ID in the object then you can use a "theta join" where you explicitly specify the association like a normal SQL Join. E.g.

FROM Phone p, Student s
WHERE p.sid = s.id
like image 39
EdC Avatar answered Sep 21 '22 16:09

EdC