spring-data-mongodb
spring-data-mongodb copied to clipboard
Explore if it makes sense to provide an EvaluationContextExtension supports optional/null query parameters.
Using @Query to skip entire criteria entries when given a null value is cumbersome at the moment but could be done as follows.
interface Repo extends CrudRepository<Person,...> {
@Query("""
{ $and : [
?#{T(com.example.Repo.QueryUtil).ifPresent([0], 'name')},
?#{T(com.example.Repo.QueryUtil).ifPresent([1], 'city')},
...
]}
""")
List<Person> findByNameAndCity(@Nullable String name, @Nullable String city, ...);
class QueryUtil {
public static Document ifPresent(Object value, String property) {
if(value == null) {
return new Document("$expr", true); // always true
}
return new Document(property, value); // eq match
}
}
// ...
}
Providing an EvaluationContextExtension with predefined methods might help ease a lot of pain.