本文介绍了弹簧靴.如何传递Optional<>到实体类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 spring 制作一个网站,我偶然发现了这个基本场景,我不知道如何解决这个特定的代码:Entity = Optional;

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 请求类):

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

RoomRepository Class:

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

推荐答案

根据您的错误,您正在从存储库的 findAll 方法中获取 Optional 并将其转换为 RoomEntity.

According to your error you are getting Optional<RoomEntity> from repository's findAll method and you are casting it to RoomEntity.

代替 RoomEntity roomEntity = roomRepository.findById(roomId); 这样做

可选optinalEntity = roomRepository.findById(roomId);RoomEntity roomEntity = optionalEntity.get();

这篇关于弹簧靴.如何传递Optional&lt;&gt;到实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:40