So I'm going through various resources trying to learn Spring Boot and Rest API and I've encountered the same problem in several different tutorials and textbooks. It seems to stem from the CrudRepository interface and more specifically the JpaRepository.findById() method.
Every tutorial I've read has something to the effect of:
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUserById(@PathVariable("id") final Long id){
UserDTO user = userJpaRepository.findById(id);
if (user == null) {
return new ResponseEntity<UserDTO>(
new CustomErrorType("User with id " + id + " not found"),
HttpStatus.NOT_FOUND);
}
return new ResponseEntity<UserDTO>(user, HttpStatus.OK);
However, the UserDTO user = userJpaRepository.findById(id);
won't compile.
I figured out if I change it to UserDTO user = userJpaRepository.findById(id).get();
it compiles, runs, and the GET is successful. The problem is if the user ID isn't found in the GET request it doesn't return NULL and I get a 500 internal server error.
The tooltips and suggestions from my IDE corrected the code to
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUserById(@PathVariable("id") final Long id){
Optional<UserDTO> user = userJpaRepository.findById(id);
if (user == null) {
return new ResponseEntity<UserDTO>(
new CustomErrorType("User with id " + id + " not found"),
HttpStatus.NOT_FOUND);
}
return new ResponseEntity<UserDTO>(HttpStatus.OK);
}
Which works just as it should for the GET request and error handling. Why do all the tutorials have it listed the first way? Could someone explain to me what is going on here?