如何解决Spring Boot如何将Optional <>传递给实体类
根据您的错误,您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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。