0

How should I check, that I receive an entity from DB and return correct response? I use restController. I want to check that I receive a user from DB or not. If I found the user, I want to return the user and HttpStatus.OK, if not - HttpStatus.NOT_FOUND.

public ResponseEntity<User> getUser(@PathVariable("id") int id) {
        User User= this.userService.getUserById(id);
        ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
        if (Objects.nonNull(user)) {
            responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
        }
        return responseEntity;
    }

3 Answers3

1

In simple terms, if you want to use Optional for checking availability of user in the database:

public ResponseEntity<User> getUser(@PathVariable("id") int id) {
    User User= this.userService.getUserById(id);
    ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    if (Optional.ofNullable(user).isPresent()) {
        responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
    }

    return responseEntity;
}
Ankur Chrungoo
  • 879
  • 6
  • 15
0

Path parameters can't be made optional, you'll have to map 2 URLs to your get controller method. Try below:

@RequestMapping(method=GET, value={"/", "/{id}"})
 public ResponseEntity<User> getUser(@PathVariable Optional<Integer> id) {

    if(!id.isPresent()){
      return ResponseEntity.notFound().build();
    }
    User User= this.userService.getUserById(id);
    ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    if (Objects.nonNull(user)) {
        responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
    }
    return responseEntity;
}

This solution requires Spring 4.1+ and Java 1.8.

0

For me this an elegant way to do it, normally id is Long type

public ResponseEntity<User> getUser(@PathVariable ("id") Long id) {
            return Optional.of(this.userService.getUserById(id))
                    .map(u -> new ResponseEntity<>(u, HttpStatus.OK))
                    .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
        }
Jose
  • 114
  • 9