The problem I’m facing is, when returning Optional i get null value.As I tought the purpose of Optional type is to avoid null values I’m a bit confused now.
This is my code:
PlayerController.java
@GetMapping("/{id}")
public Optional<Player> getPlayer(@PathVariable Long id) {
return playerService.getPlayerById(id);
}
PlayerService.java
public interface PlayerService {
List<Player> getAllPlayers();
Optional<Player> getPlayerById(Long id);
}
PlayerServiceImpl.java
@Override
public Optional<Player> getPlayerById(Long id) {
return playerRepository.findById(id);
}
When I test this using Postman, for players which id actually exists I get the player object but if I put a non existing id i get null
I’ve tried then checking if player object is null to return some kind of message like so:
@Override
public Optional<Player> getPlayerById(Long id) {
Optional<Player> player = playerRepository.findById(id);
if (player == null) { // warning
//some message
;
}
But when I wrote if statement I got a warning Condition 'player == null' is always 'false'
If the warning is true how do I get null from Postman ?