我目前正在使用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);
}
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();
}
}
答案 0 :(得分:14)
根据您的错误,您从存储库的findAll方法获取Optional<RoomEntity>
,并将其转换为RoomEntity
。
而不是RoomEntity roomEntity = roomRepository.findById(roomId);
执行此操作
Optional<RoomEntity> optinalEntity = roomRepository.findById(roomId);
RoomEntity roomEntity = optionalEntity.get();
答案 1 :(得分:0)
第一个解决方案
您可以实现JpaRepository
而不是CrudRepository
,它提供了一个getOne方法,可以按预期返回RoomEntity。 (JPA为JpaRepository
,MongoDB为MongoRepository
):
public interface RoomRepository extends JpaRepository<RoomEntity, Long> {
List<RoomEntity> findAllById(Long id);
}
和
RoomEntity roomEntity = roomRepository.getOne(roomId);
请注意,如果此roomId没有RoomEntity,则会抛出EntityNotFoundException
。
第二个解决方案
CrudRepository的findById方法返回一个可选项,因此您必须正确处理它以获取RoomEntity(如果有)。例如:
RoomEntity roomEntity = optionalEntity.roomRepository.findById(roomId).get();
在这种情况下,如果此roomId没有RoomEntity,则.get()
会抛出NoSuchElementException
。
本文可能有助于理解选项:http://www.baeldung.com/java-optional
答案 2 :(得分:0)
尝试一下,它对我有用
RoomEntity roomEntity = roomRepository.findById(roomId).orElse(null);
答案 3 :(得分:0)
答案缺少一些工作要做。致电get()
之前,应先对isPresent()
进行检查。像这样:
Optional<RoomEntity> optionalEntity = roomRepository.findById(roomId);
if (optionalEntity.isPresent()) {
RoomEntity roomEntity = optionalEntity.get();
...
}
阅读有关可选内容的精彩文章:https://dzone.com/articles/using-optional-correctly-is-not-optional
答案 4 :(得分:0)
最简单的投射方式
RoomEntity roomEntity = roomRepository.findById(roomId).get();
答案 5 :(得分:0)
正如@kaush-athukorala 所说,您只需在 .get()
末尾添加 RoomEntity roomEntity = roomRepository.findById(roomId);
即可
您将拥有 RoomEntity roomEntity = roomRepository.findById(roomId).get();
答案 6 :(得分:0)
RoomEntity roomEntity = roomRepository.findById(id).get();
这将解决您的错误!