I have a web page with a search form (with name and surname fields) and a table of persons. When user inserts a name n and a surname s I have to show the persons with name like n and surname like s. When user inserts only the name I have to filter only by name and the same when user inserts only the surname.
My searchPersons method in Controller looks like:
@RequestMapping(value = RouteConfig.SEARCH_PERSONS)
public @ResponseBody Page<Person> searchPersons(@ModelAttribute Person p, Pageable pageable) {
return pazienteRepository.findAll(where(nameIsLike(p.getName())).and(surnameIsLike(p.getSurname())), pageable);
}
I write a PersonSpecifications class:
public class PersonSpecifications {
public static Specification<Person> nomeIsLike(String name) {
return (Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) ->
cb.like(cb.lower(root.<String>get(Person_.nome)), getLikePattern(name));
}
public static Specification<Person> surnameIsLike(String surname) {
return (Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) ->
cb.like(cb.lower(root.<String>get(Person_.surname)), getLikePattern(surname));
}
Now if I have name and surname my search is ok. The problem is when name or surname is not valued in the web form.
What's the best practice in this situation?
Aucun commentaire:
Enregistrer un commentaire