Hibernate inner join using hql

I am new to Hibernate. I have two tables, for example, studentand phone number, and the two tables have a common column student id. I want to make 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;
}
+5
source share
3 answers

Read the documentation again . You do not have to have a student ID in the Phone object. Rather, you should have a connection between the two objects: The phone belongs to the student:

public class Phone {
    @Id
    private Integer id;

    private String phoneNumber;

    @ManyToOne
    private Student owner;
}

Only then can you use the connections:

// selects all the phones belonging to the students named 'John'
select phone from Phone phone where phone.owner.name = 'John'
+6
source

, , , . , sid Student, hibernate . .

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

, HQL, .

FROM Phone p
JOIN p.student s

, - , , "theta join", SQL-. .

FROM Phone p, Student s
WHERE p.sid = s.id
+3

Below you will find HQL:

SELECT * FROM student ST INNER JOIN phonenumber PN ON ST.id = PN.id, where ST.Name = 'XXXX'

-3
source

All Articles