如何使用Spring Data JPA Repository从两个表中进行查询?

22

我有两个表,一个是学生表,一个是教师表。学生表与教师表之间存在多对一的关系,其中教师表的teacherId作为外键。

如果我想使用Spring Data JPA repo方法,并以findByTeacherName的方式进行查询,该怎么做呢?例如下面这样:

select * from Student S, Teacher T 
    where T.teacherName = 'SACHIN' and S.teacherId = T.teacherId

注意:我想仅使用创建有关系到TeacherHibernateMapping类的StudentHibernateMapping类的StudentRepository来查询。任何帮助都将不胜感激。
3个回答

61

在StudentRepository上将会有一个仓库方法。

List<Student> findByTeacher_TeacherId(String teacherId);

你的entityClass应该像这样..

@Entity
Class Student {
  @Id
  String studentId;
  @ManyToOne
  private Teacher teacher;
}

并且教师班级将会是...

@Entity
Class Teacher {
  @Id
  private String teacherId;
}

你需要知道的关键是:

findBy + (学生类中外键成员的首字母大写)+下划线+教师类中数据成员的大写字母+(String teacherId);

这将给出属于该老师的学生列表。


1
好的解决方案。我想知道这种方法是否有文档记录。到目前为止,我还没有找到任何相关的资料。 - Liang Zhou
1
嗨@LiangZhou,这是你需要的链接: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation 我们甚至不需要在方法中添加下划线.. 例如: List<Student> findByTeacherTeacherId(String teacherId); 这也可以工作。 - Prateek Singh

8

关于@prateek-singh的实体,也可以仅通过外部实体而不需要id来定义查询。

List<Student> findByTeacher(Teacher teacher);


1
这对我也适用,以及由Prateek Singh提供的一个。 - Sabir Khan

3

有很多方法可以做到这一点,阅读方法命名的惯例,解释了嵌套属性的使用,或者对于更复杂的查询使用@Query注释


感谢@zoran。特别是,我想了解像在where子句中组合2个表这样的东西是否支持,比如 findByTeacherIdAndStudentId ,但我知道它可以用NativeSQL工作。 - Hariprasath Sankaraiyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接