Mehmet Ergülcü

Example Dynamic Query

· 1 min

javaspring-bootjpah2

Two ways to filter with Spring Data JPA when the client decides which fields to filter on:

  • Query by Example: fill a probe object with the values to match; empty fields are ignored.
  • Specifications: combine small predicates, which can also express "one of" and "starts with".

The application starts with 14 demo products (electronic, food, clothes) in an H2 database.

./mvnw spring-boot:run      # Java 25; http://localhost:8080

curl "localhost:8080/productlist/byfilter?type=food&name=apple"      # Query by Example, fields combined with AND
curl "localhost:8080/productlist/byfilter?name=AN&match=CONTAINS"    # case-insensitive substring
curl "localhost:8080/productlist/byspec?types=food,clothes"          # Specifications

Every predicate in ProductSpecifications returns Specification.unrestricted() for an empty input, so they combine freely with Specification.allOf. % and _ in the input are matched literally.

The Query by Example part is explained in the post Dynamic Filtering Spring JpaRepository.

Source code: github.com/ergulcu/exampledynamicquery

© 2026 Mehmet Ergülcü SvelteKit · Tailwind · <1 KB JS