如何解决获取正确的查询以获取多对多春季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",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 "
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。