javaspringjpaspring-data-jpacrud

How to find objects using JpaRepository with multiple non-requiered request parameters?


I need to find some objects for all 3 non-required parameters from request with pagination:

@GetMapping
public ResponseEntity<List<Book>> getBooks(@RequestParam(value = "name", required = false) String bookName,
                                            @RequestParam(value = "description", required = false) String bookDescription,
                                            @RequestParam(value = "status", required = false) String bookStatus,
                                            @RequestParam("page") int pageNumber,
                                            @RequestParam("size") int pageSize) {

}

But if any one of parameters is null, i need to find objects for last 2 parameters, and if any 2 of parameters is null, have to find objects for last one parameters. Please help, how can i do that searching easily with jpaRepository methods without many if cycles?

I read about JpaSpecificationExecutor and Specification. But I don't fully understand, is this exactly what I need?


Solution

  • You probably need to use custom query. Put something like this in your repository class:

    @Query("SELECT c FROM <YOUR_TABLE> c WHERE (:name is null or c.name = :name) and (:description is null or c.description = :description) and (:status is null or c.status = :status)")
    List<Role> findRoleByNameAndDescriptionAndStatus(@Param("name") String name, @Param("description") String description, @Param("status") String status);
    

    Source: https://www.baeldung.com/spring-data-jpa-null-parameters