Home > Back-end >  Course has many students and many students belong to one course. How to find to which course a parti
Course has many students and many students belong to one course. How to find to which course a parti

Time:10-08

there is a one to many unidirectional mapping from course to students

@Entity
Course {
@OnetoMany
List<Student> students;
}
@Entity
Student {
name;
age;
}

the database schema looks like Course id name duration fee

Student rollno name age course_id

I am using Jpa repository for getting.

Can anyone please tell how to tell in which course a particular student belong to? Please note that i am not using bi-directioal mapping so student entity class has no reference to course.

CodePudding user response:

Your problem is in the database deign. No performant code will rescue you from that fate.

Typically there is a join table between Students and Courses that minimally maintains two keys - the studentId and the courseId.

Need to know the courses for a student? Select from the join table where studentId = ‘X’. Need to know students in a course? Select from the join table where courseId = ‘Y’.

CodePudding user response:

I won't comment on the DB design. But solution for this problem is simple.

Basically you need to implement the relationship correctly.

@Entity
public class Course {
  private Long id;

  @OnetoMany(mappedBy = "course")
  List<Student> students;
}

@Entity
public class Student {
  private Long id;
  private String name;
  private Integer age;

  @ManyToOne
  @JoinColumn(name="course_id")
  private Course course;
}

Then simply use the getter

  Student student = studentRepo.findStudentById(123);
  Course course = student.getCourse();

Here is the full reference: https://www.baeldung.com/hibernate-one-to-many

CodePudding user response:

Your mappings and DB schema are fine, and there is nothing overly special about your mapping situation - it is just a unidirectional mapping, and there is no need for force mapping it bidirectionally and/or fetching the student data if you don't need it.

JPQL: "Select c from Course c join c.students s where s.name = :name"

With spring boot

@Query("Select c from Course c join c.students s where s.name = ?1")
Course findCourseByStudentName(String name);

Your DB setup would need to be looked at to determine if the Course is unique - I'd guess it isn't, in which case you'll want to return a list of courses that might have this student name registered.

  • Related