javax.persistence.NoResultException: getSingleResult() did not retrieve any entities

后端 未结 8 2555
执笔经年
执笔经年 2020-12-14 09:33

i have created a namedquery with ejb to check if the username is used. When the singleResult is null, then i get the following Exception :

javax.persistence.         


        
相关标签:
8条回答
  • 2020-12-14 09:45

    Michael said: "You can catch NoResultException in the catch-clause, because the transaction won't be marked as rollback, when JPA is throwing NoResultException.". It looks like for some jpa implementations, the NoResultException will rollbak transaction, which violates jpa specification, according to this article: NoResultException marks transaction rollback

    0 讨论(0)
  • 2020-12-14 09:46

    You experience the defined behaviour when calling getSingleResult and none entry was found: A NoResultException is thrown. You can catch NoResultException in the catch-clause, because the transaction won't be marked as rollback, when JPA is throwing NoResultException. Or you can use getResultList() and check if size is exactly "1", so you know you have found your user.

    Additionally, I wouldn't return "[null]" if the user is not found, but throw a checked UserNotFoundException (to be defined). But this depends on the contract of the method you are going to implement.

    0 讨论(0)
  • 2020-12-14 09:47

    What does the method throwException do?

    Is an exception being thrown within it but you are using the prior exception's message?

    0 讨论(0)
  • 2020-12-14 09:48

    You seem to rethrow the exception in your catch block with the statement throwException(username, e);. If you expect to get the user or null without any exception this should look like the following:

    public User getUserByUsernameOrNull(String username) {
        try{
            Query q = em.createNamedQuery(User.getUserByUsername);
            q.setParameter("username", username);
            return (User) q.getSingleResult();
        } catch(NoResultException e) {
            return null;
        }
    }
    
    0 讨论(0)
  • Catch NoResultException in try-catch block and handle it as per your requirement such as returning a null value.

    Example of try-catch is detailed in the following link: http://www.javabrahman.com/j2ee/jpa/no-result-exception/

    0 讨论(0)
  • 2020-12-14 09:52

    If your application uses Spring Roo the most voted answer doesn't work: the exception is caught by the aspects and you never get the desired NoResultException. The only way to solve the issue is to use getResultList and to check for zero, one or more results in the resulting List, as stated in the second most voted answer.

    0 讨论(0)
提交回复
热议问题