Reputation: 306
I need to get an object list with JpaRepository but in some cases I don`t have one of the variables in method. For example:
If I need findByNombreCursoContainsIgnoreCaseAndAreaBean but I don´t have the variable Area, what I should do? create specifics methods for each case of my queries? Exists a method in which I can pass null value for Area and get the query for all the areas?
will be
findByNombreCursoContainsIgnoreCaseAndAreaBean("example", null);
and with this get all the list with "example" and all areas.
What I'm trying to do? A searcher in my application: I think this is not optimum:
public Page<Curso> searcher(String nombreCurso, Area area, int activo, Pageable pageable){
try {
if(nombreCurso.isEmpty() && area!=null && area.getIdArea() == 0 && activo == 2) {
return getAll(pageable);
} if(area.getIdArea() == 0 && activo == 2) {
return repo.findByNombreCursoContainsIgnoreCase(nombreCurso, pageable);
} if(activo != 2 && area.getIdArea() == 0) { // 0 = descatalogado / 1 = Activo
return repo.findByNombreCursoContainsIgnoreCaseAndActivo(nombreCurso, new Integer(activo).byteValue(), pageable);
} if(activo != 2){
return repo.findByActivo(new Integer(activo).byteValue(), pageable);
}else {
return repo.findByNombreCursoContainsIgnoreCaseAndAreaBean(nombreCurso, area, pageable);
}
} catch(Exception ex) {
return getAll(pageable);
}
}
Upvotes: 0
Views: 1007
Reputation: 57
Way 1 . Try Optional
findByNombreCursoContainsIgnoreCaseAndAreaBean (..,(Optional<Area> areaOption,.){
// some code
if (optionalArgument.isPresent()) {
doSomething(optionalArgument.get());
} else {
doSomethingElse();
}
}
Way 2: While receiving data from REST
@GetMapping("/api/foos")
@ResponseBody
public void getFoos(@RequestParam(required = false) String id) {
doSomething(id);
}
OR
Using Default Value
A Default Value for the Request Parameter
@GetMapping("/api/foos") @ResponseBody public void getFoos(@RequestParam(defaultValue = "test") String id) { doSomething(id); }
Upvotes: 1
Reputation: 407
You can use org.springframework.data.domain.Example. An entity model is put into example and queried by that. Since only nombre field is set as below, query criteria is build considering just that field. If you set more fields other than null, those are also added to search criteria
Curso curso = new Curso();
curso.setNombre(5);
Page<Curso> page = cursoRepository.findAll(Example.of(curso),pageable);
https://www.baeldung.com/spring-data-query-by-example
Upvotes: 1