Spring Boot. how to Pass Optional<> to an Entity Class

前端 未结 7 1643
予麋鹿
予麋鹿 2021-02-13 16:06

i am currently making a website using spring and i stumble upon this basic scenario that i don\'t have any idea on how to solve this specific code: Entity = Optional;

         


        
7条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 17:06

    The answers lack some job to do. Before you call get(), you should do some checking with isPresent(). Like so:

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

    Read this great article about optionals: https://dzone.com/articles/using-optional-correctly-is-not-optional

提交回复
热议问题