简体   繁体   English

Spring JPA从findById()创建ResponseEntity

[英]Spring JPA Create ResponseEntity from findById()

In a spring boot application, I have an endpoint that returns a HTTP 200 response with an object if it exists, or a HTTP 404 reponse if not. 在Spring启动应用程序中,我有一个端点,如果它存在,则返回带有对象的HTTP 200响应,否则返回HTTP 404响应。 Using spring-boot-starter-parent 1.5.7 I used to do that like this: 使用spring-boot-starter-parent 1.5.7我曾经这样做:

@Autowired private GroceryRepository groceryRepository;

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public ResponseEntity<Object> get(@PathVariable final Integer id) {
    final Grocery grocery = groceryRepository.findOne(id);
    if (null == grocery) {
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(MessageUtil.parse(MSG_404_GROCERY, id + ""));
    }
    return ResponseEntity.ok(grocery);
}

GroceryRepository extends JpaRepository<Grocery, Integer>

In spring-boot-starter-parent 2.0.0, findOne() has disappeared from JpaRepository, and findById() returns an Optional . 在spring-boot-starter-parent 2.0.0中, findOne()已从JpaRepository中消失, findById()返回一个Optional I'm struggling a bit on how to 'port' the above code. 我在如何“移植”上面的代码方面有点挣扎。 The following doesn't build, since it has an unexpected return type: 以下不构建,因为它具有意外的返回类型:

groceryRepository.findById(id).ifPresent(grocery -> {
    return ResponseEntity.ok(grocery);
});

Can someone tell me what would be the proper way of returning the right Response? 有人能告诉我返回正确响应的正确方法是什么?

Thanks for any help! 谢谢你的帮助!

ifPresent has a void return type so performing return ResponseEntity.ok(grocery); ifPresent有一个void返回类型,所以执行return ResponseEntity.ok(grocery); will not work as you've already witnessed. 不会像你已经目睹的那样工作。

That said, Optional has an isPresent() method which you can use: 也就是说,Optional有一个isPresent()方法,你可以使用它:

Optional<Grocery> groceryOptional = groceryRepository.findById(id);
if(groceryOptional.isPresent()){
    return ResponseEntity.ok(groceryOptional.get());
}else {
    return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(MessageUtil.parse(MSG_404_GROCERY, id + ""));
}

Another approach would be: 另一种方法是:

Optional<Grocery> groceryOptional = groceryRepository.findById(id);
 return groceryOptional.map(e -> ResponseEntity.ok(e))
                       .orElse(ResponseEntity
                              .status(HttpStatus.NOT_FOUND)
                              .body(MessageUtil.parse(MSG_404_GROCERY, id + "")));

Even though the above answer is correct I would go for an even better more functional solution. 即使上面的答案是正确的,我也会寻求更好的功能解决方案。

Instead of calling Optional#isPresent to check whether the Grocery object is present I would something like: 而不是调用Optional#isPresent来检查Grocery对象是否存在,我会这样:

public ResponseEntity<Object> get(@PathVariable final Integer id) {
    return groceryRepository.findOne(id)
                            .map(g -> ResponseEntity.ok(g))
                            .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body(MessageUtil.parse(MSG_404_GROCERY, id + ""));

}

I have found workaround for your issue in the following Stackoverflow link 我在以下Stackoverflow链接中找到了您的问题的解决方法

How to properly handle empty resultset with Hibernate and Spring Boot It has a neatly designed solution for this! 如何使用Hibernate和Spring Boot正确处理空结果集它有一个设计巧妙的解决方案! Hope it will help! 希望它会有所帮助!

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

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