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;
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 {
List 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