简体   繁体   English

REST API 方法获取

[英]Rest API method get

How should I check, that I receive an entity from DB and return correct response?我应该如何检查,我从数据库收到一个实体并返回正确的响应? I use restController.我使用restController。 I want to check that I receive a user from DB or not.我想检查我是否收到来自 DB 的用户。 If I found the user, I want to return the user and HttpStatus.OK, if not - HttpStatus.NOT_FOUND.如果我找到了用户,我想返回用户和 HttpStatus.OK,如果没有 - 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;
    }

In simple terms, if you want to use Optional for checking availability of user in the database:简单来说,如果你想使用 Optional 来检查数据库中用户的可用性:

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;
}

Path parameters can't be made optional, you'll have to map 2 URLs to your get controller method.路径参数不能是可选的,您必须将 2 个 URL 映射到您的 get 控制器方法。 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.此解决方案需要 Spring 4.1+ 和 Java 1.8。

For me this an elegant way to do it, normally id is Long type对我来说,这是一种优雅的方式,通常 id 是 Long 类型

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));
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM