Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for optional query parameters in repository methods [DATAMONGO-2486] #3340

Closed
spring-projects-issues opened this issue Mar 2, 2020 · 1 comment

Comments

@spring-projects-issues
Copy link

@spring-projects-issues spring-projects-issues commented Mar 2, 2020

shollander opened DATAMONGO-2486 and commented

I would be nice to be have optional parameters for a repository method/query. For example:

List<User> findByLastnameAndFirstname(String lastname, Optional<String> firstname)
 

If firstname contained a value then it would be included in the query. It it was empty then it would not be included in the query.

For example:

repository.findByLastnameAndFirstname("Smith", Optional.of("John"));
 

Would generate the following query:

{'lastname' : 'Smith', 'firstname' : 'John'}

While

repository.findByLastnameAndFirstname("Smith", Optional.of());
 

Would generate the following query:

{'lastname' : 'Smith'}

This is a simple example, but the value of this feature is realized when you have a query that contains many optional parameters. Creating all possible permutations can get very complicated. I believe having Optional would greatly simplify many use cases.

Note that while Optional can currently be used in a repository method parameter, it does not behave as expected. The current behavior is to query for a null value when passed Optional.empty(). I believe this is counter-intuitive since Spring Data MongoDB does not normally insert null fields in the database. If a field has a null value, that field does not exist in the mongo document


Issue Links:

  • DATACMNS-768 Support Optional on repository query parameters
    ("duplicates")
  • DATACMNS-490 Add support for optional query method parameters
    ("duplicates")
@spring-projects-issues
Copy link
Author

@spring-projects-issues spring-projects-issues commented Mar 3, 2020

Mark Paluch commented

We already support Optional as argument in the sense of being a wrapper for null. This type of conversion is handled at Spring Data Commons level for a consistent functionality across all Spring Data modules so we cannot change this kind of behavior without breaking existing code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants