Query By Example (QBE) is a Spring Data JPA feature that builds a dynamic query from a partially populated instance of your entity, using its non-null fields as the search criteria, without requiring you to write a custom query method or JPQL for every filter combination.
Key Points: • You create a "probe" -- an entity instance with only the fields you want to filter on set, leaving the rest null. • ExampleMatcher lets you customize matching behavior per property, such as case-insensitivity or partial string matching (STARTING, CONTAINING). • QBE works through the QueryByExampleExecutor interface, which JpaRepository already extends, so no extra setup is needed to use it. • It's well suited to simple, dynamic search forms but has limits -- it can't express complex conditions like ranges, OR logic across unrelated fields, or nested entity graphs as easily as the Specification API.
Example: A search form where a user can optionally filter employees by name, department, or both builds a partially populated Employee probe with just those fields set, and passes it to findAll(Example.of(probe)) to get matching results without writing a dedicated query method for every combination of filters.
Code Example:
Employee probe = new Employee();
probe.setDepartment("Engineering");
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("department", ExampleMatcher.GenericPropertyMatchers.exact())
.withIgnoreNullValues();
Example<Employee> example = Example.of(probe, matcher);
List<Employee> results = employeeRepository.findAll(example);Interview Tip: A concise interview answer is:
"Query By Example lets me build a dynamic query by populating only the fields I want to filter on in a probe entity, then passing it to findAll(Example.of(probe)) instead of writing a custom query method for every filter combination. It's great for simple dynamic search forms, though for more complex conditions like ranges or OR logic I'd reach for the Specification API instead."