Skip to content

Query creation in Spring Data – dynamic where clause

Is there a way in Spring data to dynamically form the where clause?

What I want to do is have a method (which is like the findBy / get method) which runs a WHERE and AND using the mentioned properties which are NOT NULL.

For example,

Consider the object Person [firstName, lastName, age, gender]

Our method looks something like this

findBy_IfNotNullFirstName_AndIfNotNullLastName_AndIfNotNullAge_AndIfNotNullGender(String firstName, String lastName, Integer age, String gender)




Take a look at JPA Specification and Predicate, and Even better QueryDSL, there both supported by spring data repositories. This article provide an example:

3 People found this is helpful