0

I am trying to create simple online library to learn more about Spring Boot and MongoDB. I wanted to create filter that uses one or more parametrs.

Like this: The customer list will be searchable by first name, last name, address, birth number. The user can search using one or more parameters. It will also be possible to sort by these attributes. All text searches will be functional from the specified three characters and can be any part of the text (in the infix, prefix or suffix of a string).

My questions:

1 - How can I create multi parameter filter? The only thing that comes to my mind is like this: In UserRepository:

public findByFirstNameAndLastNameAndAdressAndBirthNumber(String firstName, String lastName, String address Long birthNumber) 

But it doesnt seem right to me.

2 - How can I make all of the parameters optional since user can search other users by one or more params?

3 - How should the endpoint for this request look like? Again, the only solution that comes to my mind is: http://localhost:8080/users/{firstName}/{lastName}/{address}/{birthNumber} -> but how can I handle the endpoint if only one of this parameters will be present?

4 - How to create filter that works with the metioned infix, prefix, ... ?

knittl
  • 246,190
  • 53
  • 318
  • 364
m_novak
  • 117
  • 10

1 Answers1

2

Use MongoTemplate and Criteria API to create the queries dynamically:

 Criteria criteria = new Criteria();
 if (firstName != null) {
      criteria = criteria.and("firstName").is(firstName);
 }
 if (lastName != null) {
     criteria = criteria.and("lastName").is(lastName);
}

 Query query = new Query(criteria);
 List<Customer> customer = mongoTemplate.find(query, Customer.class);

For matching prefix suffixes and infix, use regex:

criteria.and("firstName").regex(".*name.*")

and finally, to sort dynamically:

query.with(Sort.by(new Sort.Order(Sort.Direction.DESC, "firstName"), 
                   new Sort.Order(Sort.Direction.DESC, "lastName")));

Maven dependency:

<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-mongodb</artifactId>
</dependency>

Regarding the REST API, you could use query params instead of path variables to handle the case where only one of these parameters is present:

http://localhost:8080/users?firstName=name
gkatiforis
  • 1,588
  • 9
  • 19
  • Thank you so much! This works great for my small project :) The implementation was easier than I thought. – m_novak Nov 29 '22 at 16:24