spring无法在JavaSE8中使用map函数
我正在构建一个spring boot crud应用程序,在这里我必须搜索、添加和删除客户。我将项目遵从性更改为Java8
我正在学习本教程https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/
@RequestMapping(value = "/customers/{custId}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteCust(@PathVariable int custId) {
Customer cust=cRep.findOne(custId);
return cust.map(cust1 -> {
cRep.delete(cust1);
return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("custId " + custId + " not found"));
}
但是,我得到以下错误: 方法图((cust1)->;类型Customer的{}未定义。你能帮帮我吗?提前谢谢
# 1 楼答案
您的cust变量具有Customer类的类型。例外情况是告诉您Customer类没有map方法。您可以尝试使用
Optional.ofNullable(cRep.findById(custId)).map(...).orElseThrow(...)
# 2 楼答案
如果您已经知道该ID,则不应该使用
findOne(int)
findOne
返回对目标对象的引用,而不再是Optional<T>
。这就是为什么不能使用map()
使用
findById
,它肯定会返回一个Òptional<T>
,然后您可以映射它