0

While designing a new application using spring boot. I wanted to have rest end point for finding all entities with a filter like below

GET http://foo.com/entities?firstName=test&lastName=test2

The implementation looks like below.

@RequestMapping(value = /entities, method = RequestMethod.GET)
public List<Entity> getAll(@RequestParam(value = "firstName", required = false) String firstName, @RequestParam(value = "lastName", required = false) String lastName) {
  if (firstName != null && lastName != null) {
    return entityRepository.findByFirstNameAndLastName(firstName, lastName);
  } else if (firstName != null) {
    return entityRepository.findByFirstName(firstName);
  } else if (lastName != null) {
    return entityRepository.findByLastName(lastName);
  } else {
    return StreamSupport.stream(entityRepository.findAll().spliterator(), false).collect(Collectors.toList());
  }
}

As we can see this gets a little out of hand if we have to add new parameters. What is the easiest way to mitigate this. Or should i change the design. I thought this was the standart practice?

Note. The repository is a CRUDRepository with the added methods.

2 Answers2

0

I think you should create some kind of "SearchUtils" and use Criteria API. For example:

public class SearchCriteria {

public SearchCriteria() {
}

private String firstName;

private String lastName;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

}

SearchUtils class:

public class SearchUtils {


List<Entity> search(SearchCriteria criteria){

    //use Criteria API here



}

}

And controller:

@RequestMapping(value = /entities, method = RequestMethod.GET)
public List<Entity> getAll(@Valid SearchCriteria searchCriteria) 
{
return searchUtils.search(searchCriteria);
}

Learn more about CriteriaAPI here or here

-1

The way forward is documented here https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example