Multiple query values with JPA / Sprint and Rest

2

Good morning, I need to make a query via REST where multiple IDs will be sent for example (ID: 1, ID: 2, ID: 3, etc). To search only for an ID I use findById(codigo) , but I do not know how to use multiple data. As I'm using RESTFull, how would the URI be separated by multiple data? How would my appeal be? Today I do this (for an ID)

@GetMapping("/{id}")
public ResponseEntity<OBJ> buscarPeloCodigo(@PathVariable Long codigo) {
   Optional<OBj> obj = pessoaRepository.findById(codigo);
   return obj.isPresent() ? ResponseEntity.ok(obj.get()) : ResponseEntity.notFound().build();
}

and the URI: localhost: 8080 / data / 1

    
asked by anonymous 28.09.2018 / 15:20

3 answers

0

You can send an array of ids per parameter, eg:

Assuming your ROOT URL is localhost: 8080 / data /

In your getMapping method it looks like this: @GetMapping("/{ids}")

and the method body:

public ResponseEntity<OBJ> buscarPeloCodigo(@PathVariable Long[] ids) {
    //aqui é só iterar o array
}

Notice that you now get an array of type long.

and finally call on the front end:

localhost:8080/dados/1,2,3
    
28.09.2018 / 16:02
0

My suggestion is that you send an array of codes by queryString, so you can create an iteration for each code or even a method that receives a code list and make a select in those criteria.

// recurso
@GetMapping("/")
public ResponseEntity<List<OBJ>> buscarPessoasPorCodigos(@RequestParam(value="codigos") List<Long> codigos) {
           List<OBJ> objList = findAllById(codigos);
           return objList.isEmpty() ? ResponseEntity.notFound().build() : ResponseEntity.ok(objList));
        }

// repository

List<OBJ> findAllById(Iterable<Long> ids);

// url example

http://localhost:8080/api/pessoas?codigos=1,2,3,4,5,6
    
28.09.2018 / 16:30
0

My proposal and make a good treatment to use an ExceptionHandler

@RestController
@ControllerAdvice
class Controller {

    @GetMapping(value = "list")
    public List<Object> buscarPorCodigo(@RequestParam Integer[] codigo) {
        return pessoaRepository.findById(codigo);
        /*se não for encontrado nenhuma pessoa basta dar throw
       EntityNotFoundException que vai cair no handlerEntityNotFound*/
    }

    @ExceptionHandler(EntityNotFoundException.class)
    ResponseEntity<String> handlerEntityNotFound(EntityNotFoundException ex, WebRequest web) {
        return ResponseEntity.noContent().build();
    }
}

call gets localhost:8080/list?codigo=1?codigo=2?codigo=3

    
28.09.2018 / 21:26