I am looking for a way to dynamically create parametrized queries. In essence, I want to decouple the queries from the application and make them configurable.
For instance, I want to create a query with parameters, such as
{ firstName: ?0 }
As you probably know, this is perfectly feasable in Spring data mongodb using an interface:
interface MyQuery {
@Query("{firstName: ?0}")
public Person getByFirstName(final String name);
}
But this couples my query at compile time, while I want to change them at runtime.
I can't however find a way to use this mechanism dynamically. The particular class that is used under the hood is StringBasedMongoQuery, and uses heavy reflection utilities in order to determine the query, the parameters, the returntype, etc. You can manage most of it using Groovy I think, however Annotations seem to be a pickle.
This makes me think I chose the wrong way to approach this problem.
I myself only see a few options left:
- Reimplement Spring's fancy query parsing for mongo myself (seems a lot of work)
- Implement poor man's query parameter replacement myself. (this will not be flexible, will not yield correct result on null parameters...)
I'm at loss here, it's too bad that I can't seem to use StringBasedMongoQuery standalone, it seems to be coupled to reflection.
Update:
My suggestions seem pointless here, as I noticed also Spring data mongodb's StringBasedMongoQuery does not support 'dynamic' queries with nullable parameters; in fact this is quite logical, it is quite hard to cut parts out of your query when a parameter is null, and quite impossible to do it right.
The following sheds some light on the issue: https://jira.spring.io/browse/DATAJPA-209
So it seems my possible options have shifted to:
- We make different queries and the query used depends on the parameters that are available. This creates a possible nightmare for maintanance.
- We expose a groovy or other JVM script that allows us to use one of the available Criteria-esque API's of Spring or the mongodb Java driver, that will then build the query for us. The disadvantage of this is that someone that wants to configure the queries now has to know Java in the very least.
- We make our queries null-safe where needed at the expense of readability.