Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data optional parameter in query method

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

List<Foo> findByBarAndGoo(Bar barParam, @optional Goo gooParam); 

This method must be return Foo by this condition:

bar == barParam && goo == gooParam; 

if gooParam not null. if gooParam was null then condition change to:

bar == barParam; 

Is there any solution? Can someone help me?

like image 1000
mohammad_1m2 Avatar asked Sep 22 '15 23:09

mohammad_1m2


People also ask

How do I add optional parameters in spring boot?

You can do it in three ways: Set required = false in @RequestParam annotation. Set defaultValue = “any default value” in @RequestParam annotation. Using Optional keyword.

What is difference between CrudRepository and JpaRepository?

CrudRepository mainly provides CRUD operations. PagingAndSortingRepository provide methods to perform pagination and sorting of records. JpaRepository provides JPA related methods such as flushing the persistence context and deleting of records in batch.

What is @query used for spring data?

Spring Data JPA @Query The @Query annotation declares finder queries directly on repository methods. While similar @NamedQuery is used on domain classes, Spring Data JPA @Query annotation is used on Repository interface. This frees the domain classes from persistence specific information, which is a good thing.

How does JPA handle null values?

The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.


1 Answers

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); 
like image 194
chaserb Avatar answered Sep 24 '22 23:09

chaserb