小编典典

Spring Boot。如何将Optional <>传递给实体类

spring-boot

我目前正在使用Spring创建一个网站,但偶然发现了这种基本情况,我对如何解决此特定代码一无所知:Entity = Optional;

RoomEntity roomEntity =  roomRepository.findById(roomId);

ReservationResource(API请求类):

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

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

房间实体

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

阅读 2021

收藏
2020-05-30

共1个答案

小编典典

根据您的错误,您Optional<RoomEntity>从存储库的findAll方法获取数据并将其转换为RoomEntity

而不是RoomEntity roomEntity = roomRepository.findById(roomId);这样做

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

2020-05-30