Hackforge Academy

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 + "%")
    );
}

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community