Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...