【问题标题】:JPA Repository many to oneJPA 存储库多对一
【发布时间】:2021-01-30 20:44:22
【问题描述】:

我有Student 实体和Course 实体。这是@ManyToOne 关系,即Student 一次只能参加一门课程,但课程可能有多个学生。

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String studentId;
    private String firstName;
    private String secondName;

    @ManyToOne
    @JoinColumn(name = "course_id")
    //@JsonIgnore
    private Course course;
@Entity
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String courseName;
    @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "course", orphanRemoval = true, targetEntity = Student.class)
private List<Student> students = new ArrayList<>();

我使用以下 json 发布我的数据:

    {   
        "id": 1,
        "courseName": "course134",
        "students" : [
            {
                "id" : 1,
                "studentId": "123",
                "firstName": "John1",
                "secondName": "Name1"
                
            },
            {
                "id" : 2,
                "studentId": "1234567",
                "firstName": "John2",
                "secondName": "Name2"
                
            }

然后,当我获得课程时:

    {
        "id": 1,
        "courseName": "course134",
        "students": []
    }

如何列出参加特定课程的学生? 我在 StudentRepository 中做了一个查询

    @Query("SELECT s from  Student s where s.id = :courseName")
        Optional<Student> getStudentByCourseName(String courseName);

还是不行。

这是我的存储库代码:

    @Repository
    public interface CourseRepository extends JpaRepository<Course, Long> {
        Optional<Course> findCourseByCourseName(String courseName);
        @Query("SELECT c.students FROM Course c WHERE c.courseName = :courseName")
        Optional<Student> getStudentsByCourseName(String courseName);
    }

这是我的服务方法

      public Optional<Student> findStudentByCourse(String courseName){
            return courseRepository.getStudentsByCourseName(courseName);
        }

最后是我的控制器:

@GetMapping("/student/course/{courseName}")
public ResponseEntity<Student> findCoursesWithStudentId(@PathVariable String courseName) {
    Optional<Student> byCourseName = studentService.findStudentByCourse(courseName);
    if (byCourseName.isPresent()) {
        return ResponseEntity.ok(byCourseName.get());
    } else {
        return ResponseEntity.notFound().build();
    }
}

【问题讨论】:

  • 抱歉,关于 Cotroller 代码格式。我现在不能修改它。

标签: spring jpa many-to-one


【解决方案1】:

您应该查询 Course 表,而不是 Student 表。此外,查询将返回列表,而不仅仅是一个实体,因此还要更改方法的返回类型...

@Query("SELECT c.students FROM Course c WHERE c.courseName = :courseName")
List<Student> getStudentsByCourseName(String courseName) {}

编辑 你总是可以这样做:

  1. 执行简单方法:
Course findByCourseName(String courseName) {}
  1. 然后只需简单地获取它的学生:
course.getStudents();

【讨论】:

  • 照你说的做了,虽然我没有收到数据输出,但现在Postman不再提示内部服务器错误了
  • 这很奇怪,但我为我的答案添加了一个更简单的解决方案。如果这不起作用,请告诉我们这些方法返回什么...
  • 你有一个 REST 控制器,而不是 MVC,所以它不会返回视图,只是一个 JSON...
  • 你能给我一些参考资料吗?
猜你喜欢
  • 1970-01-01
  • 2019-07-30
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-26
相关资源
最近更新 更多