jpa存储库多对一

u5i3ibmn  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(296)

我有 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();
    }
}
4xrmg8kj

4xrmg8kj1#

您应该查询课程表,而不是学生表。此外,查询将返回列表,而不仅仅是一个实体,因此还可以更改方法的返回类型。。。

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

编辑您始终可以这样做:
执行简单方法:

Course findByCourseName(String courseName) {}

然后通过一个简单的方法让学生们:

course.getStudents();

相关问题