Paging springBoot

Asked

Viewed 530 times

1

I’m new to Spring and web development and I’m having problems paging a select, this is the method that makes 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?());

}

Besides the doubt about what is the last parameter of the returned Pageimpl, I have also doubts about how to manipulate the return of this method, I tried this 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());

1 answer

1

Why specify the total number of items?

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

In the implementation of Pageimpl 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 manipulate the return of this method?

The method getAllPeople ends up returning a Page, and from all 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. Maybe you are not paying properly within the database.

References

How to get List from Page in Spring Data REST

https://stackoverflow.com/questions/38809580/how-to-get-list-from-page-in-spring-data-rest

Browser other questions tagged

You are not signed in. Login or sign up in order to post.