Spring Boot 如何将Optional lt;gt;传递给实体类

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

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

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

解决方法

我目前正在使用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();
    }
}
总结

以上是真正的电脑专家为你收集整理的Spring Boot。如何将Optional &lt;&gt;传递给实体类的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得真正的电脑专家网站内容还不错,欢迎将真正的电脑专家推荐给好友。

你可能想看:
标签: 电脑
分享给朋友: