views:

693

answers:

4

Hello,

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

+1  A: 

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;
    }
}
codescape
perfect. Thank you very much.
A: 

What does the method throwException do?

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

JRL
+1  A: 

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

ewernli
A: 

You experience the defined behaviour when calling getSingleResult and none entry was found: A NoResultException is thrown. Because it is RuntimeException, "catch Exception" won't fit. 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.

Michael Konietzka