Return search HQL JAVA

Asked

Viewed 132 times

0

I have the following function that searches in BD 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();

}

When I pass login and password that exist in BD is fine, but what will return if the search comes up empty, I tried to compare the returned value with null, but he did not recognize the condition

1 answer

0


According to the documentation the shape made to indicate the absence of 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 search using the method getResultList, even if the result is empty, it will not launch a exception, then you only check if the returned list is empty, if negative returns the first item of 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);
}
  • 2

    It’s usually bad to return null (Uncle Bob, in his book Clean Code, is one who comments on it), you force an unnecessary check on another(s) point(s) of the program and create a potential bug point. Much better would be, in the catch, simply return a Usuario emptiness.

  • 1

    Yes, forces an external check, in this specific case I think the best would be to return a Boolean reporting success or failure, would not have the risk of an NPE or checks at all points that the code is used

Browser other questions tagged

You are not signed in. Login or sign up in order to post.