javax.persistence.NoResultException:getSingleResult()没有检索任何实体 [英] javax.persistence.NoResultException: getSingleResult() did not retrieve any entities

查看:505
本文介绍了javax.persistence.NoResultException:getSingleResult()没有检索任何实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用ejb创建了一个namedquery来检查用户名是否被使用。
当singleResult为null时,我得到以下异常:

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.

这是代码:

 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. :(

我想返回null,不会得到异常。

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

非常感谢

推荐答案

你似乎用catch语句 throwException(username,e) ; 。如果您希望获取用户或 null ,无任何例外,应如下所示:

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

这篇关于javax.persistence.NoResultException:getSingleResult()没有检索任何实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆