问题描述
任何人都可以帮助正确的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",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);
}
[
{
"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,"students": [
{
"id": 1,"courses": [
{
.......
我猜我的查询有误,我们将不胜感激。
解决方法
这可能是由于双向映射导致无限递归而发生的。
您可以使用
@JsonManagedReference
和
@JsonBackReference
与实体
在您的情况下使用
@JsonManagedReference
与学生实体和
@JsonBackReference
与课程实体一起使用,它将在尝试对结果进行序列化时防止循环
查询将是这样
"select s.courses from Student s join s.courses where s.id = :id "