Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;

RoomEntity roomEntity =  roomRepository.findById(roomId);

ReservationResource(API request Class):

    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 Class:

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

RoomEntity

@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();
    }
}
like image 605
kurt estacion Avatar asked May 05 '18 02:05

kurt estacion


2 Answers

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();

like image 163
hiren Avatar answered Sep 19 '22 03:09

hiren


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

like image 31
Jan Bodnar Avatar answered Sep 19 '22 03:09

Jan Bodnar