您好,我有一个关于可选的问题。 当有可能返回 null 时应使用可选。 我想用它来按项目 ID 查找图像。 所以在 DAO 中:
@Override
public Optional findImage(int itemId) {
Session currentSession = entityManager.unwrap(Session.class);
return currentSession
.createQuery("select from Image as i where it.itemId=:itemId")
.setParameter("itemId", itemId)
.setMaxResults(1)
.getResultList()
.stream()
.findFirst();
}
服务中:
@Override
public Image findImage(int itemId) {
LOGGER.info("Getting image by item id: {}", itemId);
Optional opt = this.imageDAO.findImage(itemId);
return opt.orElseThrow(() -> new ImageNotFound("The image for item with id: " + itemId + " was not found"));
}
但我无法获取该值或抛出特定错误。
任何人都可以解释我应该如何通过可选方式获取单个结果吗?
谢谢!!
最佳答案
编辑
正如@Slaw所提到的,我之前的答案是不正确的,我假设问题中发布的代码没有编译问题。无论如何,这是根据@Slaw 的评论更新的答案。
基本上,代码无法编译,因为它无法推断要返回的Optional 的类型。所以只需参数化可选
@Override
public Image findImage(int itemId) {
LOGGER.info("Getting image by item id: {}", itemId);
Optional<Image> opt = this.imageDAO.findImage(itemId); <== parameterize Optional
return opt.orElseThrow(() -> new ImageNotFound("The image for item with id: " + itemId + " was not found"));
}
关于java - 对 getSingleResult 使用可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55346441/