kurt estacion
kurt estacion

Reputation: 507

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

Upvotes: 24

Views: 59075

Answers (9)

Rajesh Patel
Rajesh Patel

Reputation: 180

You can try with:

Boolean roomEntity = roomRepository.existsById(roomId);

Check if exists then return true else false

OR

RoomEntity roomEntity = roomRepository.getById(roomId);

    if(roomEntity != null) {
    }

OR

This method is deprecated in new version. if you are using older version then it will work fine.


Optional<RoomEntity> roomEntity = roomRepository.getOne(roomId);

   if(roomEntity.isPresent()) {
   }

Upvotes: 0

RoshanS
RoshanS

Reputation: 129

You can use one of this ,

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

OR

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

Upvotes: 0

SHASHANK JAIS
SHASHANK JAIS

Reputation: 87

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

This will solve your error!

Upvotes: 2

Amir SHIRALI POUR
Amir SHIRALI POUR

Reputation: 21

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

Upvotes: 0

Kaush Athukorala
Kaush Athukorala

Reputation: 1

The shortest way of doing this casting

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

Upvotes: 0

Jan Bodnar
Jan Bodnar

Reputation: 11647

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

Upvotes: 11

fahed ghodhbane
fahed ghodhbane

Reputation: 89

Try this, it works for me

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

Upvotes: 7

S&#233;bastien Helbert
S&#233;bastien Helbert

Reputation: 2210

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

Upvotes: 2

hiren
hiren

Reputation: 1812

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

Upvotes: 69

Related Questions