Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 804
Hariprasath Sankaraiyan Avatar asked Nov 14 '14 20:11

Hariprasath Sankaraiyan


People also ask

How do I join two entities in JPA?

You can also use the relationship attributes in JPQL queries to join related entities. The trouble starts as soon as you want to join 2 entities without a relationship attribute. JPA and Hibernate versions prior to 5.1 don't support this kind of joins, and you have to use a workaround to create an implicit cross join.


1 Answers

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

like image 171
Prateek Singh Avatar answered Oct 13 '22 08:10

Prateek Singh