I use Optional
in my Spring Boot project, but I am not sure if I also need to pass it to Controller as return type. So, could you pls clarify me about the following issues?
Here is the example code to describe my question better:
repository:
Optional<Product> findByCode(String code);
service:
public Optional<Product> findByCode(String code) {
return productRepository.findByCode(code)
.orElseGet(Optional::empty);
}
controller:
@GetMapping("/products/{code}")
public ResponseEntity<Optional<Product>> findByCode(@PathVariable String code) {
Optional<Product> product = productService.findByCode(code);
if (product.isPresent()) {
return new ResponseEntity<>(product, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
1. I think we use Optional
, when the result may be empty. For example, in the previous situation, there may be no product for the given code. Is that all, or may there be some other common examples that make us to use of Optional
?
2. In the given example, I try to use something in the service method, but it is not working. But I really have no idea if I should use Optional
as return value to the Controller. So, could you give a proper service and Controller method example for this service method?