#hibernate #spring-data-jpa #many-to-many
#переход в спящий режим #spring-data-jpa #многие ко многим
Вопрос:
Кто-нибудь может помочь с правильным запросом JPQL для получения курсов для студентов?
@Entity
@Table(name = "students")
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinTable(name = "students_courses",
joinColumns = {
@JoinColumn(name = "student_id", referencedColumnName = "id",
nullable = false, updatable = false)},
inverseJoinColumns = {
@JoinColumn(name = "course_id", referencedColumnName = "id",
nullable = false, updatable = false)})
private Set<Course> courses = new HashSet<>();
...
и
@Entity
@Table(name = "courses")
public class Course implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
@ManyToMany(mappedBy = "courses", fetch = FetchType.LAZY)
private Set<Student> students = new HashSet<>();
...
В репозитории для студентов я создал следующий запрос JPQL :
public interface StudentRepository extends CrudRepository<Student, Long> {
/*THE QUERY SHOULD GO HERE */
@Query("")
List<Course> getStudentCourses(Long studentId);
}
Который я вызываю из StudentController:
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
public StudentRepository studentRepository;
@GetMapping("/{id}/courses")
public List<Course> getStudentCourses(@PathVariable("id") Long id){
return studentRepository.getStudentCourses(id);
}
Я перепробовал много запросов, но получаю следующий ответ postman:
[
{
"id": 1,
"title": "Machine Learning",
"abbreviation": "ML",
"modules": 12,
"fee": 1500.0,
"students": [
{
"id": 1,
"name": "John Doe",
"age": 15,
"grade": "8th",
"courses": [
{
"id": 1,
"title": "Machine Learning",
"abbreviation": "ML",
"modules": 12,
"fee": 1500.0,
"students": [
{
"id": 1,
"name": "John Doe",
"age": 15,
"grade": "8th",
"courses": [
{
.......
Я предполагаю, что у меня неправильный запрос, любая помощь будет высоко оценена.
Ответ №1:
Это может происходить из-за двунаправленного отображения, которое приводит к бесконечной рекурсии. Вы можете использовать @JsonManagedReference
и @JsonBackReference
с объектами, В вашем случае используйте @JsonManagedReference
с объектом student и @JsonBackReference
с объектом course, что предотвратит зацикливание при попытке сериализации результата
Запрос будет примерно таким
"select s.courses from Student s join s.courses where s.id = :id "