Skip to content
Advertisement

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)

Thanks.

Advertisement

Answer

Take a look at JPA Specification and Predicate, and Even better QueryDSL, there both supported by spring data repositories. This article provide an example: http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

3 People found this is helpful
Advertisement