I have some consistency issue with the Optionals in Java.
According to the documentation:
public T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable
If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.
But in my code it doesn't throw (and I've checked it for being null with the "isPresent()" method. What am I missing? Take a look at my code below and feel free to ask questions.
public AttractionOverview getAttractionOverviewById(int attraction_id) throws NoSuchElementException {
Optional<AttractionOverview> overview = this.attractionOverviewRepository.findAttractionOverviewById(attraction_id);
overview.isPresent();
return overview.<RuntimeException>orElseThrow(RuntimeException::new);
}
(I have placed a breakpoint at the line: overview:isPresent() and according to the debugger the value (when I select an id that does not exist) the value is false: meaning according to how I interpret the documentation it should throw the provided exception.
EDIT Some more context: I'm working in a SpringBoot application with a JPARepository. The orElseThrows doesn't work there. But when I simply do this in Java:
public class OptionalThrows {
public static void main(String[] args) throws Exception {
Optional<Object> empty = Optional.empty();
Object aThrow = empty.orElseThrow(() -> new RuntimeException("Nothing to see here"));
System.out.println(aThrow);
}
}
Then it works fine. Is it a springboot issue perhaps?