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