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;
}
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With