Optional.of expects pure value. You can find the info in documentation as well,
/**
* Constructs an instance with the described value.
*
* @param value the non-{@code null} value to describe
* @throws NullPointerException if value is {@code null}
*/
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
example,
jshell> Optional.of(100)
$2 ==> Optional[100]
jshell> Optional.of(null)
| Exception java.lang.NullPointerException
| at Objects.requireNonNull (Objects.java:221)
| at Optional.<init> (Optional.java:107)
| at Optional.of (Optional.java:120)
| at (#1:1)
If your value could be null at runtime, you can use .ofNullable,
jshell> Optional.ofNullable(null)
$3 ==> Optional.empty
ALSO
The idea of functional programming is to return a value for all the inputs, instead of throwing Exception which breaks the function composition.
jshell> Function<Integer, Optional<Integer>> f = x -> Optional.of(x + 1)
f ==> $Lambda$23/0x0000000801171c40@6996db8
jshell> Function<Integer, Optional<Integer>> g = x -> Optional.of(x * 2)
g ==> $Lambda$24/0x0000000801172840@7fbe847c
jshell> f.apply(5).flatMap(x -> g.apply(x))
$13 ==> Optional[12]
So in your example you can treat Optional.empty() as item not found, but Spring will consider that as 200 as well which is still better than throwing 500. You might want to send 404 to be accurate.
@GetMapping(
value = "/compras",
produces = "application/json"
)
public Optional<Compras> retrieveAllCompras(@RequestParam String id) {
return Optional.ofNullable(compraRepository.findById(id)); //will response as 200 even when no item found
}
You can use ResponseEntity<A> to set specific http status
The traditional way of responding 404 is defining specific exception.
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;
@GetMapping(
value = "/compras",
produces = "application/json"
)
public Compras retrieveAllCompras(@RequestParam String id) {
return Optional.ofNullable(compraRepository.findById(id))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "item not found"))
}