Query by Example - hibernate


#1

I am trying to query using the Example class from hibernate this way:

 public List<T> QueryByExample(T entity) throws Exception{
        try {
            
 Example exemplo = Example.create(entity).enableLike(MatchMode.ANYWHERE).ignoreCase();
    Criteria criteria = session.createCriteria(clazz);
    criteria.add(exemplo);

    return criteria.list();
            
          
        } catch (Exception e) {
            
     throw new Exception(e.getMessage());
        }
        
    
    }
 I call this method this way:
 FuncionarioDAO fDAO = new FuncionarioDAO();
        try {
fDAO.begin();
            Funcionario funcionario = new Funcionario();
            funcionario.setLogin(usuario);
            funcionario.setarSenha(senha, senha);
            List<Funcionario> resultado = fDAO.QueryByExample(funcionario);
 fDAO.commit();
 } catch (Exception e) {

    fDAO.rollback();
}

It is giving no error, but it is returning a void List, (resultado.size() is 0)
and i am sure that there is an entry in the database with the same values that i am setting in the example object.
I checked these values with debug, and they are identical, but i always get a void list as a result;

when using createQuery I can get the correct result but I want to make this queryByExample Method to work properly.

What am i missing here?


#2

Both Hibernate Criteria and query by example are deprecated and will be removed in future versions of Hibernate.

Better switch to JPA Criteria which does not have a QBE mode since it’s less powerful than expressing filtering criteria explicitly.