0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

Consultas dinâmicas com especificações

Crie consultas flexíveis programaticamente.

Consultas dinâmicas com especificações é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 1 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.

The Problem with Static Queries

When users can filter by many optional fields, writing one query method per combination explodes quickly.

Spring Data Specifications let you build queries dynamically at runtime based on which filters are present.

JpaSpecificationExecutor

Extend JpaSpecificationExecutor on your repository to enable Specification-based queries.

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

A Specification

A Specification<T> describes a single WHERE predicate using the JPA Criteria API.

Specification<User> hasName(String name) {
    return (root, query, cb) ->
        cb.equal(root.get("name"), name);
}

Executing a Specification

Pass the spec to findAll.

List<User> users =
    userRepository.findAll(hasName("Alice"));

Combining with and

Specifications compose with and, or, and not.

Specification<User> spec =
    hasName("Alice").and(isActive(true));
List<User> users = userRepository.findAll(spec);

Building Conditionally

The real power: add predicates only when the filter is supplied.

Specification<User> spec = Specification.where(null);
if (name != null) {
    spec = spec.and(hasName(name));
}
if (active != null) {
    spec = spec.and(isActive(active));
}
return userRepository.findAll(spec);

Like and Comparison Predicates

The Criteria builder offers many predicate types.

Specification<User> nameLike(String part) {
    return (root, query, cb) ->
        cb.like(root.get("name"), "%" + part + "%");
}

Specification<User> olderThan(int age) {
    return (root, query, cb) ->
        cb.greaterThan(root.get("age"), age);
}

Joining Related Entities

Specifications can navigate joins to filter on associated entities.

Specification<User> inCity(String city) {
    return (root, query, cb) ->
        cb.equal(root.join("address").get("city"), city);
}

Specifications with Paging

Combine a Specification with a Pageable for filtered, paginated results.

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

Counting Matches

count accepts a Specification too.

long matches = userRepository.count(hasName("Alice"));

Reusing Predicate Factories

Group spec factories in a helper class so they can be reused and unit tested.

public class UserSpecs {
    public static Specification<User> active() {
        return (root, q, cb) ->
            cb.isTrue(root.get("active"));
    }
}

Quick Check

Test your understanding of Specifications.

Recap

You learned dynamic querying:

  • Extend JpaSpecificationExecutor
  • A Specification is one Criteria predicate
  • Compose with and/or, add conditionally
  • Combine with Pageable for filtered pages

Perguntas Frequentes

A aula “Consultas dinâmicas com especificações” é grátis?

Sim — o texto completo de “Consultas dinâmicas com especificações” é 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 “Consultas dinâmicas com especificações”?

Crie consultas flexíveis programaticamente. 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 1 de 4.

Quanto tempo leva a aula “Consultas dinâmicas com especificações”?

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