0

everyone. I got the following criteria API:

public Optional<File> findById(Integer id) {
    @Cleanup var session = sessionFactory.openSession();
    var cb = session.getCriteriaBuilder();
    var criteria = cb.createQuery(File.class);
    var from = criteria.from(File.class);
    criteria.select(from);
    from.fetch("author", JoinType.INNER);
    criteria.where(cb.equal(from.get("id"), id));
    return Optional.ofNullable(session.createQuery(criteria).getSingleResult());
}

Which returs an entity File by it's Id and it also join fetches User entity which is "author" in File entity. So my problem is that when this query doesn't find any files it throws "no result for query" exception. But I expect null which I surrounded in Optional. Why does it throw exception instead of null even though any time I used criteria before it would return null? (if query doesn't find a result).

Also I will add a query from hibernate to prove that criteria is working right:

Hibernate: 
select
    f1_0.id,
    a1_0.id,
    a1_0.username,
    f1_0.file_path,
    f1_0.name 
from
    files f1_0 
join
    users a1_0 
        on a1_0.id=f1_0.author_id 
where
    f1_0.id=?
  • `getSingleResult` does just that, return a single result or throw an exception. That is how it is documented and implemented. – M. Deinum May 09 '22 at 10:14
  • What can I use instead that would return null(if query doesn't find any results), considering I need to use joins and stuff? I don't think I can pass criteria as a parameter in session.find() method –  May 09 '22 at 10:20
  • Nothing. You either get a single result or a list and check the size. – M. Deinum May 09 '22 at 11:33

0 Answers0