Java 如何在同一条线上使用map和ORELSERTOW?
我想从可选对象构造一个对象,如果可选对象不存在,则抛出一个异常Java 如何在同一条线上使用map和ORELSERTOW?,java,spring,spring-mvc,spring-boot,Java,Spring,Spring Mvc,Spring Boot,我想从可选对象构造一个对象,如果可选对象不存在,则抛出一个异常 @GetMapping("/{productId}") public ProductResponse getOneProduct(@PathVariable Long productId) { Optional<Product> foundProductOpt = productRepository.findById(productId); return foundProductO
@GetMapping("/{productId}")
public ProductResponse getOneProduct(@PathVariable Long productId) {
Optional<Product> foundProductOpt = productRepository.findById(productId);
return foundProductOpt.map(() ->
new ProductResponse(product, "ok").orElseThrow(() ->
new EntityNotFoundException("Product with id " +
productId + "was not found"));
}
@GetMapping(“/{productId}”)
public ProductResponse getOneProduct(@PathVariable Long productId){
可选的foundProductOpt=productRepository.findById(productId);
返回foundProductOpt.map(()->
新产品响应(产品“正常”).OrelsThrow(()->
new EntityNotFoundException(“id为的产品”+
productId+“未找到”);
}
我一直在谷歌上搜索,似乎无法以这种方式使用map方法,即我希望使用findById查找产品,然后将其放入foundProductOpt变量,然后使用找到的产品以及消息实例化响应对象
如何将对象从可选对象传递到方法或构造函数中,或者在对象不存在时引发异常?您不需要映射任何内容。如果不存在,只需引发异常。下面是我的想法: 首先,假设可选对象是真实对象,并且一切正常
return new ProductResponse(foundProductOpt
, "ok");
然后使用orelsetrow()
转换可选的
您应该更改此行:
return foundProductOpt
.map(() -> new ProductResponse(product, "ok")
.orElseThrow(() -> new EntityNotFoundException(
"Product with id " + productId + "was not found"));
致:
正确格式化如此长的行可以提高可读性。此外,您没有正确使用和
return foundProductOpt
.map(() -> new ProductResponse(product, "ok")
.orElseThrow(() -> new EntityNotFoundException(
"Product with id " + productId + "was not found"));
return foundProductOpt
.map(p -> new ProductResponse(p, "ok"))
.orElseThrow(() -> new EntityNotFoundException(
"Product with id " + productId + "was not found"));