Issue
I have a table called StudentLesson with a primary Composite Key StudentLessonPk which is made up of Student_id and Lesson_id. I would like to get the student lessons by id but of course I cannot pass an object to a path variable. I am very new to spring JPA any help is much appreciated. My code for reference:
@Embeddable
public class StudentLessonPK implements Serializable{
private static final long serialVersionUID = 5611658036387185008L;
@Column(name = "Student_Id")
private String Student_Id;
@Column(name = "Lesson_Id")
private String Lesson_Id;
//GETTERS AND SETTERS
public String getStudent_Id() {
return Student_Id;
}
public void setStudent_Id(String student_Id) {
Student_Id = student_Id;
}
public String getLesson_Id() {
return Lesson_Id;
}
public void setLesson_Id(String lesson_Id) {
Lesson_Id = lesson_Id;
}
//CONSTRUCTOR
public StudentLessonPK(String student_Id, String lesson_Id) {
super();
Student_Id = student_Id;
Lesson_Id = lesson_Id;
}
public StudentLessonPK(){
}
}
my incorrect Get Request in my controller: I would like to achieve something like /studentslesson/{studentid}/{lessonid}
@RequestMapping(value="/studentslesson/{StudentLessonPK}", method = RequestMethod.GET)
public StudentLesson StudentLessonById(@PathVariable StudentLessonPK id) {
return StudentLessonService.getStudentLesson(id);
}
my StudentLesson Service class:
public StudentLesson getStudentLesson(StudentLessonPK id) {
Optional<StudentLesson> optionalStudentLesson = studentLessonRepository.findById(id);
if(optionalStudentLesson.isPresent()) {
return optionalStudentLesson.get();
}
return null;
}
My repository:
public interface StudentLessonRepository extends CrudRepository<StudentLesson, StudentLessonPK> {
}
Solution
In your controller, you can define studentId and lessonId as two different path parameters, construct a StudentLessonPK object from the two parameters and then pass it to StudentLessonService.
@RequestMapping(value="/studentslesson/{studentId}/{lessonId}", method = RequestMethod.GET)
public StudentLesson StudentLessonById(@PathVariable String studentId, @PathVariable String lessonId) {
StudentLessonPK id = new StudentLessonPK(studentId, lessonId);
return StudentLessonService.getStudentLesson(id);
}
Answered By - Ranjith
Answer Checked By - Candace Johnson (JavaFixing Volunteer)