Abhishek
Abhishek

Reputation: 1267

Pagination in Spring Book JPA with Nested loops

I am trying to implement Pagination. I am having two tables, a teacher and a student. For each teacher, there are multiple students. Now I got a list of TeacherNames and for each teacher, I have to find all its students and add them to the list, and finally return it. I am getting page number and size also as input.




List<TeacherEntity> teacher = TeacherRepo.findByName(TeacherNames);
Teachers.forEach(teacher - > {
    List<Student> students = studentRepo.findByTeacherName(teacher);
    studentDTO.addAll(students);
});

return StudentDTO;

I know how to implement pagination if I had to query only in teachersRepo. But I am not able to get how will I do it when there is nesting.

Upvotes: 0

Views: 932

Answers (1)

Sridhar Patnaik
Sridhar Patnaik

Reputation: 1118

I am assuming that you have @ManyToMany relationship between student and teacher. If not, you have to create one before you proceed. Sample code to create relation

public class Teacher
{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long teacherId;
    
    //some fields
    
    @ManyToMany(fetch=FetchType.EAGER,cascade = CascadeType.ALL)
    @JoinTable(name = "teacher_student", joinColumns = {
            @JoinColumn(name = "teacherId", referencedColumnName = "techerId") }, inverseJoinColumns = {
                    @JoinColumn(name = "studentId", referencedColumnName = "studentId") })

    @BatchSize(size = 20)
    private Set<Stident> students = new HashSet<>();
//Get and set
}

Now, in teacher repo, add a method having join between student and teacher

@Repository
public interface TeacherRepo extends JpaRepository<Teacher, Long>
{   
    @Query(value="SELECT t.teacherName,s.studentName FROM Teacher t left join t.students s")
    public ArrayList<User> findByStudent(Pageable paging);
}

Call this repo method in your sevice class

public ArrayList<Teacher> findByStudent() 
    {
        // TODO Auto-generated method stub
        Pageable paging = PageRequest.of(0, 4);
        return teacherRepo.findByStudent(paging);
    }

This way you pagination will return 4 students records.

Note - You can add where conditions, paginations, sorting details according to your requirement

Upvotes: 1

Related Questions