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

前端 未结 7 1664
予麋鹿
予麋鹿 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 16:46

    RoomEntity roomEntity = roomRepository.findById(id).get();

    This will solve your error!

    0 讨论(0)
  • 2021-02-13 16:49

    Try this, it works for me

    RoomEntity roomEntity = roomRepository.findById(roomId).orElse(null);

    0 讨论(0)
  • 2021-02-13 16:53

    First solution

    You can implement JpaRepository instead of CrudRepository which provide a getOne method that returns an RoomEntity as you expect. (JpaRepository for JPA or MongoRepository for MongoDB) :

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

    and

    RoomEntity roomEntity = roomRepository.getOne(roomId);
    

    Note that an EntityNotFoundException will be thrown if there's no RoomEntity for this roomId.

    Second solution

    The findById method of CrudRepository returns an optional so you must deal with it properly to get an RoomEntity if there is one. For example :

    RoomEntity roomEntity = optionalEntity.roomRepository.findById(roomId).get();
    

    In this case .get() will throw a NoSuchElementException if there's no RoomEntity for this roomId.

    This article may help to understand optionals : http://www.baeldung.com/java-optional

    0 讨论(0)
  • 2021-02-13 17:03

    According to your error you are getting Optional<RoomEntity> from repository's findAll method and you are casting it to RoomEntity.

    Instead of RoomEntity roomEntity = roomRepository.findById(roomId); do this

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

    0 讨论(0)
  • 2021-02-13 17:05

    As @kaush-athukorala said, you need just add .get()at the end of RoomEntity roomEntity = roomRepository.findById(roomId); It works

    You'll have RoomEntity roomEntity = roomRepository.findById(roomId).get();

    0 讨论(0)
  • 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<RoomEntity> 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

    0 讨论(0)
提交回复
热议问题