春季启动.如何将可选<>传递给实体类

kur*_*ion 6 java spring-boot

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

RoomEntity roomEntity =  roomRepository.findById(roomId);
Run Code Online (Sandbox Code Playgroud)

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);}
    }}
Run Code Online (Sandbox Code Playgroud)

RoomRepository类:

public interface RoomRepository extends CrudRepository<RoomEntity, Long> {
    List<RoomEntity> findAllById(Long id);
}
Run Code Online (Sandbox Code Playgroud)

RoomEntity

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Hir*_*ren 23

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

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

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


小智 7

试试这个,它对我有用

RoomEntity roomEntity = roomRepository.findById(roomId).orElse(null);

  • 这是不正确的;它违背了“Optional”本身的目的。引入“Optional”是为了避免使用“null”值。如果我们确实想为变量分配一个不存在的值,我们应该使用Optional.empty()。 (2认同)

Jan*_*nar 7

答案缺乏一些工作要做。在你打电话之前get(),你应该做一些检查isPresent()。像这样:

Optional<RoomEntity> optionalEntity =  roomRepository.findById(roomId);
if (optionalEntity.isPresent()) {
    RoomEntity roomEntity = optionalEntity.get();
    ...
}
Run Code Online (Sandbox Code Playgroud)

阅读这篇关于可选项的精彩文章:https : //dzone.com/articles/using-optional-correctly-is-not-optional