Multiple query values with JPA/Sprint and Rest

Asked

Viewed 131 times

2

Good morning, I need to make a query via REST where multiple ID will be sent for example (ID: 1, ID: 2, ID:3, etc). To search only for an ID I use findById(codigo), but I don’t know how to use multiple data. As I am using Restfull, how would the URI be separated by multiple data? What would my appeal look like? Today I do so(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

3 answers

0


You can send an array of ids per parameter, e.g.:

assuming that your ROOT URL is localhost:8080/data/

in your getMapping method gets like this: @GetMapping("/{ids}")

and the body of the method:

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

note that you now receive an array of the long type.

and finally to calling for in the front end:

localhost:8080/dados/1,2,3

0

My suggestion is that you send a code array by queryString, so you can create an iteration for each code or even a method that receives a code list and select on 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);

// example url

http://localhost:8080/api/pessoas?codigos=1,2,3,4,5,6
  • Perfect my dear, thank you very much.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.