简体   繁体   English

在 JPA 中使用父实体获取子实体

[英]Fetch a child entity using parent entity in JPA

I have these given below entities and I want to execute some queries and I am not sure how to do it in JPA.我在下面给出了这些实体,我想执行一些查询,但我不确定如何在 JPA 中进行。

School.java学校.java

@Data
@Builder
public class School {
    private String schoolName;
    private int schoolId;
    private List<Grade> grades;
}

Grade.Java等级.Java

@Data
@Builder
public class Grade {
    private String grade;
    private int gradeId;
    private List<Student> students;
}

Student.java学生.java

@Data
@Builder
public class Student {
    private String studentName;
    private int studentId;
    private List<Subject> subjects;
}

Subject.java主题.java

@Data
@Builder
public class Subject {
    private String subjectName;
    private int subjectId;
}

I need to execute these queries:我需要执行这些查询:

  1. Get all Students By schoolId通过 schoolId 获取所有学生
  2. Get all Students By gradeId通过gradeId获取所有学生
  3. Get all Students By schoolId & gradeId通过 schoolId 和 GradeId 获取所有学生

How can this be achieved?如何做到这一点?

First, please go through the JPA documentation a bit.首先,请仔细阅读JPA 文档 Look for Native Queries .查找本Native Queries

For example for first one:例如第一个:

1) Get all Students By schoolId 1)通过schoolId获取所有学生

@Query("SELECT s FROM Student s WHERE s.school_id = :schoolId")
List<Student> findStudentsBySchoolId(@Param("schoolId") Long schoolId);

Considering you have following:考虑到您有以下几点:

  • A mapping of School in Student with mapping column schoolId .带有映射列schoolId StudentSchool映射。
  • And offcourse a repository for Student in which above method will go.并为学生提供一个存储库,上面的方法将在其中运行。 You might also want to extend JPARepository .您可能还想扩展JPARepository

Also Note另请注意

List<Student> findBySchool_SchoolId(Long id);

It is not a very good idea to name your methods with underscore in Java .Java中用下划线命名方法不是一个好主意。 See this 看到这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM