弹簧靴。如何将 Optional<> 传递给实体类

新手上路,请多包涵

我目前正在使用 spring 制作一个网站,我偶然发现了这个基本场景,我不知道如何解决这个特定代码:Entity = Optional;

 RoomEntity roomEntity =  roomRepository.findById(roomId);

ReservationResource(API请求类):

     public class ReservationResource {
    @Autowired
    RoomRepository roomRepository;

    @RequestMapping(path = "/{roomId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<RoomEntity> getRoomById(
    @PathVariable
    Long roomId){
        RoomEntity roomEntity =  roomRepository.findById(roomId);
        return new ResponseEntity<>(roomEntity, HttpStatus.OK);}
    }}

RoomRepository 类:

 public interface RoomRepository extends CrudRepository<RoomEntity, Long> {
    List<RoomEntity> findAllById(Long id);
}

房间实体

@Entity
@Table(name = "Room")
public class RoomEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    private Integer roomNumber;

    @NotNull
    private String price;

    public RoomEntity() {
        super();
    }
}

原文由 kurt estacion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 445
2 个回答

根据您的错误,您从存储库的 findAll 方法中获取 Optional<RoomEntity> 并将其转换为 RoomEntity

而不是 RoomEntity roomEntity = roomRepository.findById(roomId); 这样做

Optional<RoomEntity> optinalEntity = roomRepository.findById(roomId); RoomEntity roomEntity = optionalEntity.get();

原文由 hiren 发布,翻译遵循 CC BY-SA 4.0 许可协议

答案缺少一些工作要做。在调用 get() 之前,您应该使用 isPresent() 进行一些检查。像这样:

 Optional<RoomEntity> optionalEntity =  roomRepository.findById(roomId);
if (optionalEntity.isPresent()) {
    RoomEntity roomEntity = optionalEntity.get();
    ...
}

阅读这篇关于可选的精彩文章: https ://dzone.com/articles/using-optional-correctly-is-not-optional

原文由 Jan Bodnar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题