Why in JPA EntityManager queries throw NoResultException but find does not?

后端 未结 4 1642
暗喜
暗喜 2020-12-10 02:48

Can somebody tell me the intrinsic reasons why in the JPA 1.0 EntityManager when retrieving an Object via find, you have to deal with null if not found, but when using the Q

4条回答
  •  忘掉有多难
    2020-12-10 03:25

    I think it eliminates this null check :

    Object o = q.getSingleResult();
    if (o != null)
      return (MyObj) o;
    return o;
    

    By introducing a RuntimeException (NoResultException) , programmers can safely cast q.getSingleResult() to MyObj , and leave the exception to the caller.

    As to q.getResultList() , it will always return a list , null-check is not necessary.

    But I still feel this non-intuitive.

提交回复
热议问题