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

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.

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

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 StudentHibernateMapping class that has a relationship to TeacherHibernateMapping class

Any help will greatly be appreciated.

Upvotes: 22

Views: 33494

Answers (3)

lilalinux
lilalinux

Reputation: 3031

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

List<Student> findByTeacher(Teacher teacher);

Upvotes: 8

Prateek Singh
Prateek Singh

Reputation: 1114

There will be a repository method on StudentRepository

List<Student> findByTeacher_TeacherId(String teacherId);

your entityClass should be like..

@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);

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

Upvotes: 61

Zoran Regvart
Zoran Regvart

Reputation: 4680

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

Upvotes: 3

Related Questions