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

8

22

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

Chintzy answered 10/4, 2010 at 10:55 Comment(0)
L
38

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;
    }
}
Liable answered 10/4, 2010 at 11:0 Comment(0)
B
13

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

Beverly answered 10/4, 2010 at 11:47 Comment(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/…Outhaul
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.Outhaul
K
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.

Kaslik answered 10/4, 2010 at 12:6 Comment(1)
Can you elaborate on: "because it is runtimeexception "catch exception" won't fit".. Why not?Carpentry
F
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

Fitts answered 6/3, 2011 at 1:31 Comment(0)
C
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.

Chef answered 27/1, 2017 at 11:39 Comment(0)
I
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;
        }
Innerve answered 8/12, 2020 at 3:3 Comment(0)
C
0

What does the method throwException do?

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

Cathouse answered 10/4, 2010 at 11:13 Comment(0)
Q
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/

Quimper answered 20/6, 2014 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.