Hello I have a question about Optional. Optional should be used when there is possibility then null can be returned. I wanted to use it to find the image by item id. So in 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();
}
In service:
@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"));
}
But I can not get the value or throw the specific error.
Can anybody explain how I should approach the getting single result via Optional?
Thanks!!