[英]Join 3 tables in a ManytoMany relationship using JpaRepository
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).
问题是:我有 2 个课程:学生和课程,每门课程可以有很多学生,每个学生可以有很多课程,(你可以看到下面的代码)。 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).我想要做的是在使用
@Query
实现的学生存储库接口中使用@Query,它给了我学生的名字和这个学生遵循的课程名称(我不在乎我是否需要打印每个名字每门课程的时间)但我不知道如何执行连接查询,因为 che 表“course_like”存在于 db 中但不在 java 中(因为是一个集合,我使用注释在 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;
}
}
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.