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

【字号: 日期:2024-03-23浏览:40作者:雯心
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解决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(); }}

相关文章: