#mysql #spring #hibernate #spring-boot
#mysql #spring #переход в спящий режим #spring-boot
Вопрос:
У меня есть таблица с именем StudentLesson с первичным составным ключом StudentLessonPk, который состоит из идентификаторов Student_id и Lesson_id. Я хотел бы получать уроки учащихся по идентификатору, но, конечно, я не могу передать объект в переменную path. Я очень новичок в spring JPA, любая помощь очень ценится. Мой код для справки:
@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(){
}
}
мой неправильный запрос Get в моем контроллере: я хотел бы добиться чего-то вроде /studentslesson/{studentid} /{lessonid}
@RequestMapping(value="/studentslesson/{StudentLessonPK}", method = RequestMethod.GET)
public StudentLesson StudentLessonById(@PathVariable StudentLessonPK id) {
return StudentLessonService.getStudentLesson(id);
}
мой класс обслуживания StudentLesson:
public StudentLesson getStudentLesson(StudentLessonPK id) {
Optional<StudentLesson> optionalStudentLesson = studentLessonRepository.findById(id);
if(optionalStudentLesson.isPresent()) {
return optionalStudentLesson.get();
}
return null;
}
Мой репозиторий:
public interface StudentLessonRepository extends CrudRepository<StudentLesson, StudentLessonPK> {
}
Ответ №1:
В вашем контроллере вы можете определить StudentID и LessonID как два разных параметра пути, создать объект StudentLessonPK из двух параметров, а затем передать его в 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);
}
Комментарии:
1. Спасибо! Мне просто нужно было добавить правильные параметры, и все было хорошо. @RequestMapping(значение=»/studentslesson/{Student_Id}/{Lesson_Id}», метод = RequestMethod. ПОЛУЧАЕМ) общедоступный идентификатор STUDENTLESSON StudentLessonById(@PathVariable String Student_Id, @PathVariable String Lesson_Id) {Идентификатор StudentLessonPK = новый идентификатор StudentLessonPK(Student_Id, Lesson_Id); возвращаем studentLessonService.getStudentLesson(id); }