简体   繁体   中英

How to get data when query select inner join many table in Spring Data JPA

This is my project. I having problem, I want to get data from table Student join many table branch, room, and gender use annotation @Query as site query in the image MySql

This is query with statement MySql

This is code I want to use @Query in Spring Data JPA with purpose get data when join many table

After I call API, It notify error This is error

I need to support, this is my project: https://github.com/daovantam0410/quan-ly-dao-tao

You have two options here, you can use get the students from the database.

List<Student> students = studentRepository.findAll();

This will load the other entities (room, gender and branch) by issuing other queries and this will lead to the famous problem N+1 queries

So to load all the entities in one go, use entity graphs or fetch join

@Query(value = "SELECT st FROM Student st INNER JOIN FETCH st.branch b INNER JOIN FETCH st.gender g INNER JOIN FETCH st.room r")
List<Student> fetchStudentDataJoinTable();

Note : If the properties ( room , gender and branch ) can be null in student then use left join instead of inner join .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM