我正在学习springBoot框架的教程。netbeans显示以下代码的错误。错误为incompatible type:Optional<UsersDTO> cannot be converted to UserDTO
@GetMapping("/{id}")
public ResponseEntity<UsersDTO>getUserById(@PathVariable("id") final Long id){
UsersDTO user = userJpaRepository.findById(id);
return new ResponseEntity<UsersDTO>(user,HttpStatus.OK);
} 发布于 2020-09-24 18:07:40
JPA Repository findById返回Optional,因为可能找不到该项目。
因此,此代码无法编译,因为返回类型错误且与findById不匹配
您需要有正确的类型,这是可选的,如下所示:
Optional<UsersDTO> user = userJpaRepository.findById(id);有了这个项目后,您可以检查user.isPresent()和user.get()以获取UsersDTO对象(如果它存在)。
https://stackoverflow.com/questions/64044094
复制相似问题