I was updating the dependencies to Spring 5 in my project and was bombarded with compilation errors where the method definition of findOne()
has been replaced by findById()
which now returns an Optional
(correct me if I am wrong).
While refactoring, I came across multiple approaches that I can choose to adopt, and I would therefore like some input on which one is to be preferred.
1st approach:
ExpectedPackage ep = expectedPackageRepository.findById(1).orElse(null); if(ep != null){ ep.setDateModified(new Date()); expectedPackageRepository.saveAndFlush(ep); }
2nd approach:
Optional<ExpectedPackage> ep = expectedPackageRepository.findById(1); if(ep.isPresent()){ ep.get().setDateModified(new Date()); expectedPackageRepository.saveAndFlush(ep.get()); }
Or is there a third and better approach that I have missed? I went through several questions and a couple of articles, but I did not find a clear answer.
In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.
Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null . It should always point to an Optional instance.
The orElse() method of java. util. Optional class in Java is used to get the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method returns the specified value.
Based on their Javadocs: orElse(): returns the value if present, otherwise returns other. orElseGet(): returns the value if present, otherwise invokes other and returns the result of its invocation.
You can also do:
expectedPackageRepository.findById(1).ifPresent( ep -> { ep.setDateModified(new Date()); expectedPackageRepository.saveAndFlush(ep); } );
Ideally, you would also extract the part between brackets ({}
) to a separate method. Then, you could write like this:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep) { ep.setDateModified(new Date()); expectedPackageRepository.saveAndFlush(ep); }
You can read the documentation of ifPresent
here: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-
As it states, it will perform the specified action if the value is present and do nothing otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With