Spring Data JPA query with optional paramters

261 Views Asked by At

I have an GET endpoint which fetches the data based on the below parameters. firstName is mandatory and rest all are optional.

{

"firstName:"",
"lastName:"",
"Gender:"",
"city"""

}

How should i approach for the database query? i am using Sring Data JPA, I have tried

findByFirstNameOrLastNameOrGenderOrCity(firstName,lastName,Gender,City)

Not sure if a native sql query using @Query annotation will work as any of the values apart from firstName can be null if the consumer of the endpoint is not sending the values. Kindly help

1

There are 1 best solutions below

2
On

If you need something like this:

GET /myEntities?firstName=bla-bla&lastName=bla-bla&gender=1&city=bla-bla

where firstName is mandatory and rest all are optional,

then you can use like this query:

@Query("select e from MyEntity e where e.firstName = ?1 " +
    "and (?2 is null or e.lastName = ?2) " + 
    "and (?3 is null or e.gender = ?3) " +
    "and (?4 is null or e.city = ?4)")
List<MyEntities> getByFilter(String firstName, String lastName, Boolean gender, String city);