20

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.NoResultException: getSingleResult() did not retrieve any entities

But this exception is the result that i want when the username is free.

Here is the code:

 public User getUserByUsername(String username) throws DAOException{
    try{
        Query q = em.createNamedQuery(User.getUserByUsername);
        q.setParameter("username", username);
        return (User) q.getSingleResult();
    }catch(Exception e){
        throwException(username, e);
        return null;
    }
}

Does anybody know what the problem is. :(

I would like to return null and don`t get an Exception.

Thank you very much

0

8 Answers 8

37

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
12

Use getResultList instead and check if the List is empty (has zero element). Otherwise, the list contains one element and you simply return it.

2
  • This should be the preferred answer, as it avoids the exception handling block, which in this case, JPA seems to have foisted upon the client. blog.takipi.com/…
    – michaelok
    Nov 4, 2016 at 15:58
  • Guava's Iterables class, specifically the getFirst method, shows how the exception for a non-exceptional case can be avoided: getFirst 'Returns the first element in iterable or defaultValue if the iterable is empty.
    – michaelok
    Nov 4, 2016 at 18:46
3

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.

1
  • Can you elaborate on: "because it is runtimeexception "catch exception" won't fit".. Why not? Oct 5, 2013 at 12:25
2

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
1

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.

1
try {
            Query queryObj = entityMgrObj
                    .createQuery("SELECT u FROM UserEntity u WHERE u.email = :email AND u.password = :password");
            queryObj.setParameter("email", email);
            queryObj.setParameter("password", password);
            UserEntity userEntity = (UserEntity) queryObj.getSingleResult();

            return userEntity;

        } catch (NoResultException e) {
            return null;
        }
0

What does the method throwException do?

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

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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.