Spring Data optional parameter in query method

后端 未结 4 1026
有刺的猬
有刺的猬 2020-12-02 22:21

I want to write some query methods in repository layer. This method must ignore null parameters. For example:

List findByBarAndGoo(Bar barParam,          


        
相关标签:
4条回答
  • 2020-12-02 22:36

    You could code this yourself in just a few lines:

    List<Foo> findByBarAndOptionalGoo(Bar bar, Goo goo) {
       return (goo == null) ? this.findByBar(bar) : this.findByBarAndGoo(bar, goo);
    }
    

    Otherwise, I don't know if Spring-Data supports this out of the box.

    0 讨论(0)
  • 2020-12-02 22:43

    I don't believe you'll be able to do that with the method name approach to query definition. From the documentation (reference):

    Although getting a query derived from the method name is quite convenient, one might face the situation in which either the method name parser does not support the keyword one wants to use or the method name would get unnecessarily ugly. So you can either use JPA named queries through a naming convention (see Using JPA NamedQueries for more information) or rather annotate your query method with @Query

    I think you have that situation here, so the answer below uses the @Query annotation approach, which is almost as convenient as the method name approach (reference).

        @Query("select foo from Foo foo where foo.bar = :bar and "
            + "(:goo is null or foo.goo = :goo)")
        public List<Foo> findByBarAndOptionalGoo(
            @Param("bar") Bar bar, 
            @Param("goo") Goo goo);
    
    0 讨论(0)
  • 2020-12-02 22:48

    Too late to answer. Not sure about relationship between Bar and Goo. Check if Example can helps you.

    It worked for me. I have a similar situation, entity User have set of attributes and there is findAll method which search user based on attributes(which are optional).

    Example,

      Class User{
        String firstName;
        String lastName;
        String id;
      }
    
      Class UserService{
         // All are optional
         List<User> findBy(String firstName, String lastName, String id){
            User u = new User();
            u.setFirstName(firstName);
            u.setLastName(lastName);
            u.setId(id);
    
            userRepository.findAll(Example.of(user));
            // userRepository is a JpaRepository class
         }
      }
    
    0 讨论(0)
  • 2020-12-02 22:49

    Complementing the answer of @chaserb, I personally would add the parameter as a Java8 Optional type to make it explicit in the signature of the method the semantics that is an optional filter.

    @Query("select foo from Foo foo where foo.bar = :bar and "
       + "(:goo is null or foo.goo = :goo)")
    public List<Foo> findByBarAndOptionalGoo(
         @Param("bar") Bar bar, 
         @Param("goo") Optional<Goo> goo);
    
    0 讨论(0)
提交回复
热议问题