I'm using the Spring-data-mongodb repository framework in my Spring Boot project. I have an API where users can specify 1+ query parameters when searching for an object, and I would like to convert those query parameters to search criteria using the @Query
annotation.
Since the number of search fields would not be consistent as users can specify a varying number of query parameters, I cannot hardcode fieldnames like the official documentation examples show. I tried putting together some SpEl strings to do this "dynamic exclusion" of criteria within the @Query
annotation, but Spring is escaping the strings I'm returning so I'm unable to concatenate a query together piecemeal. Is there a way to do this using the @Query
annotation alone?
(I don't want to declare a repository extension, write Java code calling Spring Mongo DSL methods, nor use the QueryByExample
framework. I just want to stick with the @Query
annotation)
Dummy sample code:
BookRepo.java
:
@Repository
public interface BookRepo extends MongoRepository<Book, String> {
// Want to make the fields dynamic in this query so that if "author" or "publisher" is null/blank, then it's not included in the query
@Query("{'author': ?0, 'publisher': ?1}")
List<Book> getAllBooksBy(String author, String publisher);
}