spring-data-mongodb icon indicating copy to clipboard operation
spring-data-mongodb copied to clipboard

Explore if it makes sense to provide an EvaluationContextExtension supports optional/null query parameters.

Open christophstrobl opened this issue 3 years ago • 0 comments

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.

christophstrobl avatar May 12 '22 09:05 christophstrobl