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
Asked
Active
Viewed 2,018 times
1

Jens Schauder
- 77,657
- 34
- 181
- 348

Chandan Kumar
- 313
- 4
- 9
-
Duplicate of https://stackoverflow.com/questions/11613464/spring-data-mongo-optional-query-parameters – Jens Schauder May 12 '21 at 08:18
2 Answers
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