Return search HQL JAVA

0

I have the following function that searches the DB for a user that satisfies the login and password passed by parameter:

public Usuario getUsuarioLogin(String pLogin, String pSenha) {       
    String hql = " select u from Usuario u "
               + " where u.login =:pLogin "
               + " and u.senha =:pSenha ";

    Query query = this.getManager().createQuery(hql);

    query.setParameter("pLogin", pLogin);
    query.setParameter("pSenha", pSenha);       

    return (Usuario) query.getSingleResult();

}

    
asked by anonymous 21.10.2018 / 01:24

1 answer

0

According to documentation , the form used to indicate the no result is the launch of a NoResultException .

In this case you will need to use a block try-catch to detect a return with no results and proceed as desired.

Ex:

public Usuario getUsuarioLogin(String pLogin, String pSenha) {       
    String hql = " select u from Usuario u "
               + " where u.login =:pLogin "
               + " and u.senha =:pSenha ";

    Query query = this.getManager().createQuery(hql);

    query.setParameter("pLogin", pLogin);
    query.setParameter("pSenha", pSenha);       

    try {
        return (Usuario) query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

Another way is to do the search using the method getResultList , even if the result is empty, it will not throw a exception , hence you only check if the returned list is empty, if negative returns the first item in the list:

public Usuario getUsuarioLogin(String pLogin, String pSenha) {       
    String hql = " select u from Usuario u "
               + " where u.login =:pLogin "
               + " and u.senha =:pSenha ";

    Query query = this.getManager().createQuery(hql);

    query.setParameter("pLogin", pLogin);
    query.setParameter("pSenha", pSenha); 

    List users = query.getResultList();

    if (users.isEmpty()) {
        return null;
    }
    return (Usuario) results.get(0);
}
    
21.10.2018 / 02:01