可选类型在运行时分配

huangapple go评论60阅读模式
英文:

Optional type is assigned at runtime

问题

我正在按照 Spring Boot 框架的教程进行学习NetBeans 对下面的代码显示了错误错误信息是:`不兼容的类型Optional<UsersDTO> 无法转换为 UserDTO`

@GetMapping("/{id}")
public ResponseEntity<UsersDTO> getUserById(@PathVariable("id") final Long id){
    UsersDTO user = userJpaRepository.findById(id);
    return new ResponseEntity<UsersDTO>(user, HttpStatus.OK);
}
英文:

I am following a tutorial for springBoot framework. The netbeans shows error for the below code. Error is incompatible type:Optional&lt;UsersDTO&gt; cannot be converted to UserDTO

@GetMapping(&quot;/{id}&quot;)
public ResponseEntity&lt;UsersDTO&gt;getUserById(@PathVariable(&quot;id&quot;) final Long id){
    UsersDTO user = userJpaRepository.findById(id);
    return new ResponseEntity&lt;UsersDTO&gt;(user,HttpStatus.OK);
}  

答案1

得分: 2

JPA Repository 的 findById 方法返回一个 Optional,因为可能找不到该项。

因此,这段代码无法编译,因为返回类型不正确,与 findById 的返回类型不匹配。

你需要使用正确的类型,即像这样的 Optional<UsersDTO>:

 Optional&lt;UsersDTO&gt; user = userJpaRepository.findById(id);

一旦获得了这个项,你可以通过 user.isPresent() 和 user.get() 来获取 UsersDTO 对象(如果存在)。

英文:

JPA Repository findById returns Optional, as the item may not be found.

Therefore this code doesn't compile because the return type is wrong and doesn't match findById

You need to have the right type, which is Optional<UsersDTO> like so:

 Optional&lt;UsersDTO&gt; user = userJpaRepository.findById(id);

Once you have this item you can check user.isPresent() and user.get() to obtain the UsersDTO object if it is present.

huangapple
  • 本文由 发表于 2020年9月24日 18:01:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64044094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定