0

I need to find an efficient and logical way to implement a search for a given entity, like Person. Suppose that a person has name, surname, birthDay, birthPlace etc.

In my REST-API service, the client app can search people by only its name, surname and mixed them, so all the parameters may be optional. I don't want to make a lot of if(person.name!=null){em.setParamet(":name",person.name);....

How can I do this in an intelligent way?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
I love coding
  • 1,183
  • 3
  • 18
  • 47
  • I would go with query parameters, build a query object and submit that to a dedicated service method `getByQuery`. Then, i would conditionally add parameters (for example, if `query.hasName()`, then add `query.getName()`) to a JPA Criteria Query. Still some mapping is required, but this may be a viable solution. – Glains Jun 29 '20 at 09:20
  • 1
    Use JPA specifications for this purpose. https://stackoverflow.com/questions/46970689/multi-column-search-with-spring-jpa-specifications or use Criteria API directly https://stackoverflow.com/questions/12199433/jpa-criteria-api-with-multiple-parameters – Eklavya Jun 29 '20 at 09:21
  • Thank you, could please just make an answer with an example, in order to get the point? – I love coding Jun 29 '20 at 09:21
  • 1
    Does this answer your question? [Spring Data - Multi-column searches](https://stackoverflow.com/questions/25872637/spring-data-multi-column-searches) – Eklavya Jun 29 '20 at 09:27

0 Answers0