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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With