对 getSingleResult 使用 Optional
Using Optional for getSingleResult
您好,我有一个关于可选的问题。
如果有可能返回 null,则应使用 Optional。
我想用它来按项目 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"));
}
但是我无法获取值或抛出特定错误。
谁能解释一下我应该如何通过 Optional 获得单一结果?
谢谢!!
编辑
如@Slaw所述,我之前的回答是错误的,我假设问题中发布的代码没有编译问题。无论如何,这是根据@Slaw 的评论更新的答案。
基本上代码无法编译,因为它无法推断 return 的 Optional 类型。所以只需参数化 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"));
}
您好,我有一个关于可选的问题。 如果有可能返回 null,则应使用 Optional。 我想用它来按项目 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"));
}
但是我无法获取值或抛出特定错误。
谁能解释一下我应该如何通过 Optional 获得单一结果?
谢谢!!
编辑
如@Slaw所述,我之前的回答是错误的,我假设问题中发布的代码没有编译问题。无论如何,这是根据@Slaw 的评论更新的答案。
基本上代码无法编译,因为它无法推断 return 的 Optional 类型。所以只需参数化 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"));
}