Why can't I use .orElseThrow() method on an Entity?
The following method works.
@GetMapping("/usuarios/{codigo_us}")
EntityModel<Usuario> one(@PathVariable Long codigo_us) { //HATEOAS way of forwarding resources
Usuario usuario = repository.findById(codigo_us)
.orElseThrow(() -> new UsuarioNotFoundException(codigo_us));
// Spring WebMvcLinkBuilder
return assembler.toModel(usuario);
}
But when I try a slightly different approach it doesn't work.
@GetMapping("/usuarios/{cedula_us}")
EntityModel<Usuario> getByCedula(@PathVariable Long cedula_us){
Usuario usuario = repository.findByCedula_us(cedula_us).get(0)
.orElseThrow(() -> new UsuarioNotFoundException(cedula_us));
return assembler.toModel(usuario);
Different classes have different methods available.
The first method returns an Optional<Usuario>
which has method orElseThrow()
The second method returns some kind of Iterable/List/Collection, on which you call get(0) which grabs the first element Usuario
but no longer wrapped in Optional. Therefore there is no orElseThrow()
available.
You can achieve the same thing for second method by wrapping it into optional:
Usario usario = repository.findByCedula_us(cedula_us).get(0);
usario = Optional.ofNullable(usario).orElseThrow(...
This is just an example to clarify how it works, a better approach would be to add a method in the repository itself to only return first result and return optional, something like:
Optional<Usario> findFirstByCedula_us(String cedula_us)