Issue
Since i dind't find an answer to my problem i'm asking here. The problem is this: i have 2 classes : Student and Course, every course can have many student and every student can have many courses,( u can see the code below). What i want to do is to use a @Query
in the student repository interface implemented using JpaRepository, that gives me the name of the student and the course's name that this student follows (i don't care if i need to print every name many times for each course) but i don't know how to perform the join query since che table "course_like" is present in the db but not in java (since is a set and i use the annotations for create the join tablein the db). hope u can help me
Student Entity:
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@ManyToMany()
@JoinTable(
name = "course_like",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> courses;
public Student() {
}
public Student(String name, Set<Course> courses) {
this.name = name;
this.courses = courses;
}
public Student(int id, String name, Set<Course> courses) {
this.id = id;
this.name = name;
this.courses = courses;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}
Course Entity:
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@ManyToMany(mappedBy = "courses")
private Set<Student> students;
public Course(int id, String name, Set<Student> students) {
this.id = id;
this.name = name;
this.students = students;
}
public Course(int id, String name) {
this.id = id;
this.name = name;
}
public Course(String name, Set<Student> students) {
this.name = name;
this.students = students;
}
public Course() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
Solution
Below query should return all the student and course mapping. Hope this helps you.
select distinct s.name, c.name from Student s join s.courses c;
Answered By - Pradyskumar
Answer Checked By - Mildred Charles (JavaFixing Admin)