Category: spring_boot
Dynamic filtering in jpa
Published on 26 Jun 2026
Explanation
Dynamic filtering allows clients to retrieve
data based on optional criteria such
as name, email, department, or status.
Spring Data JPA supports dynamic queries
through derived query methods,
Specifications, and
custom queries.
Code:
@Entity
public class Student {
@Id
private Long id;
private String name;
private String department;
private String email;
}
Explanation
Spring Data JPA can automatically generate
queries based on method names. These
derived query methods are useful for
simple filtering requirements.
Code:
public interface StudentRepository
extends JpaRepository<Student, Long> {
List<Student>
findByDepartment(String department);
List<Student>
findByNameContaining(String name);
}
Explanation
Query parameters can be used to
pass filter values from the client.
The controller receives the filter criteria
and forwards them to the repository
layer.
Code:
@GetMapping("/students")
public List<Student> getStudents(
@RequestParam String department) {
return studentRepository.
findByDepartment(department);
}
Explanation
For multiple optional filters, custom JPQL
queries can be used. This allows
the API to apply conditions only
when filter values are provided.
Code:
@Query("SELECT s FROM Student s WHERE " +
"(:name IS NULL OR s.name
LIKE %:name%) AND " +
"(:department IS NULL OR
s.department = :department)")
List<Student> searchStudents(
@Param("name") String name,
@Param("department")
String department);
Explanation
Specifications provide a powerful way to
build dynamic queries at runtime. They
are ideal for advanced search screens
where users can filter by multiple
fields simultaneously.
Code:
public interface StudentRepository extends JpaRepository<Student, Long>,
JpaSpecificationExecutor<Student> {
}
@GetMapping("/search")
public List<Student> searchStudents(
@RequestParam(required = false) String name) {
return studentRepository.findAll(
(root, query, cb) ->
name == null ? null : cb.like(root.get("name"), "%" + name + "%")
);
}