0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

Paginação e ordenação

Retorne grandes conjuntos de dados com eficiência.

Paginação e ordenação é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Why Paginate

Returning thousands of rows at once is slow and memory-heavy. Pagination fetches one page at a time.

Spring Data provides Pageable, Page, and Sort for this.

PagingAndSortingRepository

JpaRepository already includes paging and sorting support, so you get these methods for free.

public interface UserRepository
    extends JpaRepository<User, Long> {
}

Creating a Pageable

PageRequest.of(page, size) builds a request. Page numbers are zero-based.

Pageable pageable = PageRequest.of(0, 20);
Page<User> page = userRepository.findAll(pageable);

The Page Object

A Page carries the content plus metadata.

List<User> content = page.getContent();
long total = page.getTotalElements();
int pages = page.getTotalPages();
boolean hasNext = page.hasNext();

Sorting

Build a Sort and pass it alone or inside a PageRequest.

Sort sort = Sort.by("name").ascending();
List<User> sorted = userRepository.findAll(sort);

Combining Sort and Paging

Pass a Sort into PageRequest.of.

Pageable pageable = PageRequest.of(
    0, 20, Sort.by("name").descending());
Page<User> page = userRepository.findAll(pageable);

Multiple Sort Orders

Chain sort orders for tie-breaking.

Sort sort = Sort.by(
    Sort.Order.asc("lastName"),
    Sort.Order.desc("createdAt"));

Paging Derived Queries

Add a Pageable parameter to any derived query method.

Page<User> findByActiveTrue(Pageable pageable);

Slice vs Page

A Slice knows only whether a next page exists, skipping the expensive COUNT query that Page runs. Use Slice for infinite scroll.

Slice<User> findByActiveTrue(Pageable pageable);

Pageable from the Web Layer

Spring MVC can bind page, size, and sort request params into a Pageable automatically.

@GetMapping("/users")
public Page<User> list(Pageable pageable) {
    return userRepository.findAll(pageable);
}
// GET /users?page=0&size=20&sort=name,desc

Mapping Page Content to DTOs

Transform a Page's entities to DTOs while preserving pagination metadata with map.

Page<UserDto> dtos = page.map(
    user -> new UserDto(user.getName(), user.getEmail()));

Quick Check

Test your understanding of pagination.

Recap

You learned pagination and sorting:

  • PageRequest.of(page, size) — page is zero-based
  • Page carries content plus totals; Slice skips the count
  • Sort.by(...) for ordering
  • Web layer binds page/size/sort into a Pageable

Perguntas Frequentes

A aula “Paginação e ordenação” é grátis?

Sim — o texto completo de “Paginação e ordenação” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

O que vou aprender em “Paginação e ordenação”?

Retorne grandes conjuntos de dados com eficiência. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?

Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Paginação e ordenação”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?

Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Consultas dinâmicas com especificações
  2. Projeções e DTOs
  3. Auditoria com @CreatedDate
  4. Paginação e ordenação
← Voltar para Spring Boot 4 Microservices & REST APIs