How to remove a Where from @Query in Spring Jparepository

Asked

Viewed 70 times

-1

I am using Spring BOOT with Starter JPA and java 8 and I have this query in my Repository :

    @Query("select p from Product p where p.name like %:name% and p.costValue = :costValue and p.saleValue= :saleValue")
List<Product> findByExemple(@Param("name") String name, @Param("costValue") Float costValue, @Param("saleValue") Float saleValue);

I need that when the float parameter comes null remove the condition or bring everything, it would be a % in the number field.

Example:

When the costValue parameter comes null bring all. Without the use of filter it would be like doing the Query this way :

        @Query("select p from Product p where p.name like %:name% and p.saleValue= :saleValue")
List<Product> findByExemple(@Param("name") String name, @Param("costValue") Float costValue, @Param("saleValue") Float saleValue);
  • 1

    The quickest solution would be not to use @Query Instead assemble an HQL or Criteria based on your parole

  • Or even create new ones query methods to consider or not the property, but I do not like this approach much, I prefer my first suggestion for making the code more reusable

  • 1

    I had never used HQL and with your reply I gave a researched and found the best approach. Thank you very much.

1 answer

1


The simplest form of change without the use of hql as already quoted would be to place the conditional OR in your select contemplating the null case, ex:

@Query("select p from Product p where p.name like %:name% and ( p.costValue = :costValue OR :costValue is null ) and p.saleValue= :saleValue")
List<Product> findByExemple(@Param("name") String name, @Param("costValue") Float costValue, @Param("saleValue") Float saleValue);
  • It worked perfectly thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.