Java 如何使用 Spring Data JPA Repository 从 2 个表中查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26938048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:32:37  来源:igfitidea点击:

How to use Spring Data JPA Repository to query from 2 tables?

javahibernatespring-data

提问by Hariprasath Sankaraiyan

I have 2 tables say Student and Teacher and say Student has a Many-To-One relationship to Teacher and say, teacherId serves as the foreign key.

我有 2 个表,分别是 Student 和 Teacher,并说 Student 与 Teacher 有多对一的关系,并且说,teacherId 作为外键。

How can I use spring data JPA repo methods, in a way - findByTeacherName, if I want to query something like below,

如何以某种方式使用 spring 数据 JPA 存储库方法 - findByTeacherName,如果我想查询如下内容,

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

Note : Here I wanna query using only StudentRepository, which is created using StudentHibernateMappingclass that has a relationship to TeacherHibernateMappingclass

注意:这里我想使用 only 查询StudentRepository,它是使用与StudentHibernateMapping类有关系的TeacherHibernateMapping类创建的

Any help will greatly be appreciated.

任何帮助将不胜感激。

回答by Zoran Regvart

There are an ample of ways to do that, read up on the convention of method namingthat explains the use of nested properties, or for more complex queries use @Query annotation.

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

回答by Prateek Singh

There will be a repository method on StudentRepository

StudentRepository 上会有一个存储库方法

List<Student> findByTeacher_TeacherId(String teacherId);

your entityClass should be like..

你的 entityClass 应该像..

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

and Teacher Class would be..

和教师班将是..

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

Here the key thing you need to know is:

这里你需要知道的关键是:

findBy + (the foreign key member of student class with first letter Upper) + underscore +the data member of Teacher Class with first letter UpperCase+(String teacherId);

findBy +(首字母为Upper的student类的外键成员)+下划线+首字母为UpperCase的Teacher类的数据成员+(StringteacherId);

this will give you a list of students belonging to that teacher

这将为您提供属于该老师的学生列表

回答by lilalinux

Regarding @prateek-singh's entities, it should also be possible to define the query without id at all, simply by the foreign entity.

关于@prateek-singh 的实体,也应该可以定义完全没有 id 的查询,只需通过外部实体即可。

List<Student> findByTeacher(Teacher teacher);

List<Student> findByTeacher(Teacher teacher);