The use of Hibernate / JPA getsingleresult reports an exception noresult xception:No entity found for query

Geeks, please accept the hero post of 2021 Microsoft x Intel hacking contest>>>

When using the getsingleresult() method, if there is no result (that is, null is returned), the habitual thinking is that null should be returned. However, there is such a statement in the getsingleresult() method: @ throws entitynotfoundexception if there is no result
that is to say, when he can’t find the result, he will throw entitynotfoundexception instead of null
this is very annoying. If you can’t find the result, you don’t want to throw an exception out of the business logic at any time. It’s troublesome to do exception handling because of this exception 1. Give up getsingleresult() and use uniqueresult() in hibernate; The uniqueresult() method has been marked as obsolete in Hibernate 5, but it does not affect its use. It is not clear whether it will be removed in future versions

return getSession()
            .createQuery(hql)
            .uniqueResult();

2. The insurance method is: still use the getresultlist () method, no matter you are getting one or more results, do the following processing when getting one result:

List list = getSession().createQuery(hql).getResultList();
if(list.size() > 0)
    return list.get(0);
else
    return null;

Similar Posts: