spring-data-mongo - optional query parameters?Spring Data MongoDB AND/OR query with multiple optional parametersSpring data mongodb: Optional @Query parameter no longer worksSpring Data MongoDB query with multiple optional parameters $in CollectionSpring Boot custom MongoDB query with optional parameter of $regex throws NullPointExceptionJava optional parametersDoes Java support default parameter values?How to query MongoDB with “like”?How to solve “Plugin execution not covered by lifecycle configuration” for Spring Data Maven BuildsWhat's the difference between @Component, @Repository & @Service annotations in Spring?How to list all collections in the mongo shell?What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?MongoTemplate criteria query translation seems incorrectAuto-Generated Spring data query for MongoDB: X most recent entriesSpring mongo slice array in embedded document

Is there a conventional notation or name for the slip angle?

Freedom of speech and where it applies

Is camera lens focus an exact point or a range?

What does this horizontal bar at the first measure mean?

Could solar power be utilized and substitute coal in the 19th Century

Why did the HMS Bounty go back to a time when whales are already rare?

Can somebody explain Brexit in a few child-proof sentences?

Visiting the UK as unmarried couple

Longest common substring in linear time

Can I sign legal documents with a smiley face?

Why is Arduino resetting while driving motors?

My friend sent me a screenshot of a transaction hash, but when I search for it I find divergent data. What happened?

THT: What is a squared annular “ring”?

Folder comparison

Flux received by a negative charge

Diode in opposite direction?

Do the concepts of IP address and network interface not belong to the same layer?

About a little hole in Z'ha'dum

How do I extrude a face to a single vertex

How to express sadness?

Remove Expired Scratch Orgs From VSCode

Why did the EU agree to delay the Brexit deadline?

Some numbers are more equivalent than others

Does having a TSA Pre-Check member in your flight reservation increase the chances that everyone gets Pre-Check?



spring-data-mongo - optional query parameters?


Spring Data MongoDB AND/OR query with multiple optional parametersSpring data mongodb: Optional @Query parameter no longer worksSpring Data MongoDB query with multiple optional parameters $in CollectionSpring Boot custom MongoDB query with optional parameter of $regex throws NullPointExceptionJava optional parametersDoes Java support default parameter values?How to query MongoDB with “like”?How to solve “Plugin execution not covered by lifecycle configuration” for Spring Data Maven BuildsWhat's the difference between @Component, @Repository & @Service annotations in Spring?How to list all collections in the mongo shell?What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?MongoTemplate criteria query translation seems incorrectAuto-Generated Spring data query for MongoDB: X most recent entriesSpring mongo slice array in embedded document













15















I am using spring-data mongo with the JSON based query methods, and am unsure how to allow optional parameters in a search query.



For instance - say I had the following function



@Query(" 'name' : $regex : ?0, $options : 'i', 'createdDate' : $gte : ?1, $lt : ?2 }")
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange);


-but I didnt want to apply the name regex match, or not apply a date range restriction if NULL values were passed to the method.



At the moment it looks like I might have to build the query using the mongoTemplate.



Are there any alternatives - or is using mongoTemplate the best option?



Thanks










share|improve this question






















  • For now I have gone down the route of using the Criteria classes. It does seem a lot cleaner than embedding JSON queries in annotations, and easier to customize which fields are retrieved.

    – Andrew B
    Jul 24 '12 at 9:03















15















I am using spring-data mongo with the JSON based query methods, and am unsure how to allow optional parameters in a search query.



For instance - say I had the following function



@Query(" 'name' : $regex : ?0, $options : 'i', 'createdDate' : $gte : ?1, $lt : ?2 }")
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange);


-but I didnt want to apply the name regex match, or not apply a date range restriction if NULL values were passed to the method.



At the moment it looks like I might have to build the query using the mongoTemplate.



Are there any alternatives - or is using mongoTemplate the best option?



Thanks










share|improve this question






















  • For now I have gone down the route of using the Criteria classes. It does seem a lot cleaner than embedding JSON queries in annotations, and easier to customize which fields are retrieved.

    – Andrew B
    Jul 24 '12 at 9:03













15












15








15


10






I am using spring-data mongo with the JSON based query methods, and am unsure how to allow optional parameters in a search query.



For instance - say I had the following function



@Query(" 'name' : $regex : ?0, $options : 'i', 'createdDate' : $gte : ?1, $lt : ?2 }")
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange);


-but I didnt want to apply the name regex match, or not apply a date range restriction if NULL values were passed to the method.



At the moment it looks like I might have to build the query using the mongoTemplate.



Are there any alternatives - or is using mongoTemplate the best option?



Thanks










share|improve this question














I am using spring-data mongo with the JSON based query methods, and am unsure how to allow optional parameters in a search query.



For instance - say I had the following function



@Query(" 'name' : $regex : ?0, $options : 'i', 'createdDate' : $gte : ?1, $lt : ?2 }")
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange);


-but I didnt want to apply the name regex match, or not apply a date range restriction if NULL values were passed to the method.



At the moment it looks like I might have to build the query using the mongoTemplate.



Are there any alternatives - or is using mongoTemplate the best option?



Thanks







java spring mongodb spring-data






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jul 23 '12 at 13:25









Andrew BAndrew B

1,1011527




1,1011527












  • For now I have gone down the route of using the Criteria classes. It does seem a lot cleaner than embedding JSON queries in annotations, and easier to customize which fields are retrieved.

    – Andrew B
    Jul 24 '12 at 9:03

















  • For now I have gone down the route of using the Criteria classes. It does seem a lot cleaner than embedding JSON queries in annotations, and easier to customize which fields are retrieved.

    – Andrew B
    Jul 24 '12 at 9:03
















For now I have gone down the route of using the Criteria classes. It does seem a lot cleaner than embedding JSON queries in annotations, and easier to customize which fields are retrieved.

– Andrew B
Jul 24 '12 at 9:03





For now I have gone down the route of using the Criteria classes. It does seem a lot cleaner than embedding JSON queries in annotations, and easier to customize which fields are retrieved.

– Andrew B
Jul 24 '12 at 9:03












3 Answers
3






active

oldest

votes


















18














To implement this in Boolean logic I do the following and the conversion to operations that are available in programming languages



:query != null -> field == :query
!(:query != null) || (field == :query)
(:query == null) || (field == :query)


In plain SQL, this is done as



where (null = :query) or (field = :query)


In MongoDB this is done through the $where



 


We can speed this up a little by using Mongo Operations rather than building everything to the function at the expense of some readability. does not work unfortunately.



 $or : [ $where: '?0 == null' , field : ?0 ] 


So what you have is



@Query(" $or : [ $where: '?0 == null' , field : ?0 ] ")
List<Something> findAll(String query, Pageable pageable);


This can be further expanded to handle arrays for in/all clauses



@Query(" $or : [ $where: '?0.length == 0' , field : $in : ?0 ] ")
List<Something> findAll(String query, Pageable pageable);





share|improve this answer
































    1














    You might be interested in providing feedback or vote on this issue:
    https://jira.springsource.org/browse/DATAJPA-209



    It deals with exactly this problem., except for SD JPA. Seems like it'd be appropriate for many other SD subprojects.






    share|improve this answer























    • Thanks, voted on this!

      – Andrew B
      May 13 '13 at 10:37


















    0














    The given ticket deals with finders generating their SQL by "name magic", e.g. findByTitleAndSubtitle(), which now works fine. But there is still the same problem when you annotate this finder with:



    @Query("select product where title = :title and subtitle = :subtitle"); 


    null values are translated into subtitle = null, and therefore will not be found.






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11613464%2fspring-data-mongo-optional-query-parameters%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      18














      To implement this in Boolean logic I do the following and the conversion to operations that are available in programming languages



      :query != null -> field == :query
      !(:query != null) || (field == :query)
      (:query == null) || (field == :query)


      In plain SQL, this is done as



      where (null = :query) or (field = :query)


      In MongoDB this is done through the $where



       


      We can speed this up a little by using Mongo Operations rather than building everything to the function at the expense of some readability. does not work unfortunately.



       $or : [ $where: '?0 == null' , field : ?0 ] 


      So what you have is



      @Query(" $or : [ $where: '?0 == null' , field : ?0 ] ")
      List<Something> findAll(String query, Pageable pageable);


      This can be further expanded to handle arrays for in/all clauses



      @Query(" $or : [ $where: '?0.length == 0' , field : $in : ?0 ] ")
      List<Something> findAll(String query, Pageable pageable);





      share|improve this answer





























        18














        To implement this in Boolean logic I do the following and the conversion to operations that are available in programming languages



        :query != null -> field == :query
        !(:query != null) || (field == :query)
        (:query == null) || (field == :query)


        In plain SQL, this is done as



        where (null = :query) or (field = :query)


        In MongoDB this is done through the $where



         


        We can speed this up a little by using Mongo Operations rather than building everything to the function at the expense of some readability. does not work unfortunately.



         $or : [ $where: '?0 == null' , field : ?0 ] 


        So what you have is



        @Query(" $or : [ $where: '?0 == null' , field : ?0 ] ")
        List<Something> findAll(String query, Pageable pageable);


        This can be further expanded to handle arrays for in/all clauses



        @Query(" $or : [ $where: '?0.length == 0' , field : $in : ?0 ] ")
        List<Something> findAll(String query, Pageable pageable);





        share|improve this answer



























          18












          18








          18







          To implement this in Boolean logic I do the following and the conversion to operations that are available in programming languages



          :query != null -> field == :query
          !(:query != null) || (field == :query)
          (:query == null) || (field == :query)


          In plain SQL, this is done as



          where (null = :query) or (field = :query)


          In MongoDB this is done through the $where



           


          We can speed this up a little by using Mongo Operations rather than building everything to the function at the expense of some readability. does not work unfortunately.



           $or : [ $where: '?0 == null' , field : ?0 ] 


          So what you have is



          @Query(" $or : [ $where: '?0 == null' , field : ?0 ] ")
          List<Something> findAll(String query, Pageable pageable);


          This can be further expanded to handle arrays for in/all clauses



          @Query(" $or : [ $where: '?0.length == 0' , field : $in : ?0 ] ")
          List<Something> findAll(String query, Pageable pageable);





          share|improve this answer















          To implement this in Boolean logic I do the following and the conversion to operations that are available in programming languages



          :query != null -> field == :query
          !(:query != null) || (field == :query)
          (:query == null) || (field == :query)


          In plain SQL, this is done as



          where (null = :query) or (field = :query)


          In MongoDB this is done through the $where



           


          We can speed this up a little by using Mongo Operations rather than building everything to the function at the expense of some readability. does not work unfortunately.



           $or : [ $where: '?0 == null' , field : ?0 ] 


          So what you have is



          @Query(" $or : [ $where: '?0 == null' , field : ?0 ] ")
          List<Something> findAll(String query, Pageable pageable);


          This can be further expanded to handle arrays for in/all clauses



          @Query(" $or : [ $where: '?0.length == 0' , field : $in : ?0 ] ")
          List<Something> findAll(String query, Pageable pageable);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Aug 29 '12 at 0:19

























          answered Aug 28 '12 at 18:06









          Archimedes TrajanoArchimedes Trajano

          10.2k484103




          10.2k484103























              1














              You might be interested in providing feedback or vote on this issue:
              https://jira.springsource.org/browse/DATAJPA-209



              It deals with exactly this problem., except for SD JPA. Seems like it'd be appropriate for many other SD subprojects.






              share|improve this answer























              • Thanks, voted on this!

                – Andrew B
                May 13 '13 at 10:37















              1














              You might be interested in providing feedback or vote on this issue:
              https://jira.springsource.org/browse/DATAJPA-209



              It deals with exactly this problem., except for SD JPA. Seems like it'd be appropriate for many other SD subprojects.






              share|improve this answer























              • Thanks, voted on this!

                – Andrew B
                May 13 '13 at 10:37













              1












              1








              1







              You might be interested in providing feedback or vote on this issue:
              https://jira.springsource.org/browse/DATAJPA-209



              It deals with exactly this problem., except for SD JPA. Seems like it'd be appropriate for many other SD subprojects.






              share|improve this answer













              You might be interested in providing feedback or vote on this issue:
              https://jira.springsource.org/browse/DATAJPA-209



              It deals with exactly this problem., except for SD JPA. Seems like it'd be appropriate for many other SD subprojects.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered May 1 '13 at 21:21









              Matthew AdamsMatthew Adams

              85311019




              85311019












              • Thanks, voted on this!

                – Andrew B
                May 13 '13 at 10:37

















              • Thanks, voted on this!

                – Andrew B
                May 13 '13 at 10:37
















              Thanks, voted on this!

              – Andrew B
              May 13 '13 at 10:37





              Thanks, voted on this!

              – Andrew B
              May 13 '13 at 10:37











              0














              The given ticket deals with finders generating their SQL by "name magic", e.g. findByTitleAndSubtitle(), which now works fine. But there is still the same problem when you annotate this finder with:



              @Query("select product where title = :title and subtitle = :subtitle"); 


              null values are translated into subtitle = null, and therefore will not be found.






              share|improve this answer





























                0














                The given ticket deals with finders generating their SQL by "name magic", e.g. findByTitleAndSubtitle(), which now works fine. But there is still the same problem when you annotate this finder with:



                @Query("select product where title = :title and subtitle = :subtitle"); 


                null values are translated into subtitle = null, and therefore will not be found.






                share|improve this answer



























                  0












                  0








                  0







                  The given ticket deals with finders generating their SQL by "name magic", e.g. findByTitleAndSubtitle(), which now works fine. But there is still the same problem when you annotate this finder with:



                  @Query("select product where title = :title and subtitle = :subtitle"); 


                  null values are translated into subtitle = null, and therefore will not be found.






                  share|improve this answer















                  The given ticket deals with finders generating their SQL by "name magic", e.g. findByTitleAndSubtitle(), which now works fine. But there is still the same problem when you annotate this finder with:



                  @Query("select product where title = :title and subtitle = :subtitle"); 


                  null values are translated into subtitle = null, and therefore will not be found.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 21 at 13:47









                  noob

                  5081617




                  5081617










                  answered Feb 4 '14 at 10:07









                  Uwe AllnerUwe Allner

                  2,32952637




                  2,32952637



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11613464%2fspring-data-mongo-optional-query-parameters%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현