Pagination springBoot

1

I'm new to Spring and web development and I'm having trouble paging a select, this is the method that does the search:

public static Page getAllPeople(Connection connection, Pageable pageable) {
ArrayList<peopleDto> peopleList = new ArrayList<>();
DSLContext ctx = null;
peopleDto peopleDto;
try {
    ctx = DSL.using(connection, SQLDialect.MYSQL);
    Result<Record> result = ctx.select()
            .from(people)
            .orderBy(people.GNUM)
            .offset(pageable.getOffset())
            .limit(pageable.getPageSize())
            .fetch();

    for (Record r : result) {

        peopleDto = new peopleDto();
        peopleDto.setpeopleID(r.getValue(people.GNUM));
        peopleDto.setName(r.get(people.SNAME));
        peopleDto.setRM(r.get(people.SRM));
        peopleDto.setRG(r.get(people.SRG));
        peopleDto.setCertidaoLivro(r.get(people.SCERT));
        peopleDto.setCertidaoDistrito(r.get(people.SCERTD));
        peopleList.add(peopleDto);
    }
} catch (Exception e) {
    log.error(e.toString());
} finally {
    if (ctx != null) {
    ctx.close();
    }
}
return new PageImpl(peopleList, pageable, aquiVaiOtotaldaPesquisa?());

}

In addition to the question about what is the last parameter of the returned PageImpl, I also have doubts about how to handle the return of this method, I tried that way but it does not work as expected

 Page<PeopleDto> page = AlunoManager.getAllPeople(con,PageRequest.of(páginas, tamanho));//?

if(page.hasNext())
getAllPeople(connection, page.nextPageable());
    
asked by anonymous 06.07.2018 / 13:44

1 answer

1

Why specify the total number of elements?

Note that we can create a page where each page has 10 elements inside, or each page can contain 20 elements inside or as many elements as you want on a single page according to your needs . How will I know how many pages there are in total without informing the total of existing elements? Therefore it is necessary to inform the total elements.

In the PageImpl implementation when calling the next page with page.hasNext () , the following code snippet is executed:

public int getTotalPages() {
    return this.getSize() == 0 ? 1 : (int)Math.ceil((double)this.total / (double)this.getSize());
}

public boolean hasNext() {
    return this.getNumber() + 1 < this.getTotalPages();
}

How to handle the return of this method?

The getAllPeople method ends up returning a Page , and everything is right for you to go to the next page.

public Pageable nextPageable() {
    return this.hasNext() ? this.pageable.next() : Pageable.unpaged();
}

If you are not returning the desired elements, see how your offset and limit of your select are. You may not be paging correctly within the database.

References

How to get List from Page in Spring Data REST

link

    
08.01.2019 / 20:39