1

I have a search functionality where there are different parameters and user can choose one or multiple parameters and ignore other parameters. I want to use findByFirstNameAndLastNameAndAddressAndCountry() for this so that if any parameter is null or empty it can be ignored and the And condition get applied to other parameters

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Chandan Kumar
  • 313
  • 4
  • 9

2 Answers2

0

This can be a duplicate issue. You can do it using @Query annotation and your custom Query.

Ref: How to skip @Param in @Query if is null or empty in Spring Data JPA

@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);
Senthil
  • 2,156
  • 1
  • 14
  • 19
0

Use 'Query' and 'Criteria' option provided by Spring for MongoDB.

Query query = new Query();

if(!obj.getFirstName.isEmpty()){
    Criteria criteria1 = Criteria.where('first_name').is(obj.getFirstName);
    query.add(criteria1);
}
Chandan Kumar
  • 313
  • 4
  • 9