1

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!!

Ernesto
  • 950
  • 1
  • 14
  • 31
  • 2
    Check the syntax of the query , sounds like some thing is missing here. Try `select i from Image as it where it.itemId=:itemId` – Gopi Mar 25 '19 at 21:12
  • Yeap there was a typo, but still what about optional – Ernesto Mar 25 '19 at 21:13
  • 2
    "I can not get the value or throw the specific error". Clarify. – LppEdd Mar 25 '19 at 21:13
  • 2
    You're the third one I see today unwrapping the EntityManager to use the Hibernate proprietary Session. Why are you doing that? What's the point, except making your code awkward and not portable? You can execute queries using the EntityManager directly. No need to unwrap. – JB Nizet Mar 25 '19 at 21:15
  • @JB Nizet I am learning actualy... good to know. Can you tell me about this optional? – Ernesto Mar 25 '19 at 21:18
  • I can't understand your question. Clarify. – JB Nizet Mar 25 '19 at 21:18
  • How should I handle with Optionals in service layer. If DAO method returns me Optional then what? isPresent() -> get() else throw error or what? – Ernesto Mar 25 '19 at 21:20
  • 1
    Are you asking what you can do with an Optional? The javadoc is your friend: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html. If not, then once again, clarify: what do you want to achieve, precisely? – JB Nizet Mar 25 '19 at 21:28
  • 2
    Assuming you're using `java.util.Optional`, you are returning the [_raw type_](https://stackoverflow.com/questions/2770321/). This means all the methods that return the wrapped value return `Object`. You should declare the return type as `Optional`. If that's not your problem (or really even if it is) you should [edit] your question to add clarification. Describe what you're trying to do, what's actually happening, and include the _exact_ error(s) you're getting. See [mcve] and [ask]. – Slaw Mar 25 '19 at 21:42

1 Answers1

2

EDIT

As mentioned by @Slaw, my previous answer was incorrect and I have assumed that the code posted in the question has no compilation issue. Anyway, here's the updated answer based on the @Slaw's comment.

Basically the code wouldn't compile because it's unable to infer the type of Optional to return. So just parameterize 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"));
}
Tan Kim Loong
  • 980
  • 7
  • 14
  • How is this correct? No matter what `Optional` the OP is using (`java.util.Optional` or some other), your solution assumes the wrapped value, returned by `get`, has an `orElseThrow` method. Why would it? And assuming we're using `java.util.Optional`, the `orElseThrow` method will return the value if present, otherwise it will throw the exception returned by the supplier. The `get` method will throw a `NoSuchElementException` if no value is present. And you're still using the raw type, so `get` and `orElseThrow` return `Object`, not `Image`, and this should still fail to compile. – Slaw Mar 27 '19 at 15:57
  • You are absolutely correct. I was under the assumption that the code provided in the question would already compile. A mistake on my side. You should provide your answer instead, or I will edit mine to reflect your point. Should have verified my answer properly! – Tan Kim Loong Mar 28 '19 at 03:13