Lazy Loading (PrimeFaces) - Problema com Cast no filterBy e dúvida com filterMatchMode

2 respostas
F
Bom dia pessoal, possuo uma tabela que é carregada com Lazy Loading do Primefaces, porém eu tenho um campo que é do tipo BOOLEAN, e eu crio um SelectItem[] para ser o filterBy dessa coluna boolean que ficou assim:
public SelectItem[] getStatusOptions() {  
        SelectItem[] options = new SelectItem[3];  
        options[0] = new SelectItem("", "Todos");  
        options[1] = new SelectItem(true, "Ativado");  
        options[2] = new SelectItem(false, "Desativado");  
        return options;  
    }
Porém na hora que eu escolho Ativado ou Desativado, recebo a exception: SEVERE: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean Eu gostaria de saber como eu faço pra contornar isso. A única forma seria fazendo a verificação de qual coluna estou filtrando no meu load do LazyDataModel e fazer o devido Cast? Ou existe algum converter?

Outra dúvida minha, é como eu implemento o filterMatchMode na minha table Lazy Loading? A unica forma disso também seria verificando no meu load do LazyDataModel cada coluna e fazer a devia alteração na query?

Obrigado desde já.

Meu DAO:
public class EstacionamentoDAOImpl extends DAOImpl<Estacionamento, Long> implements EstacionamentoDAO {

    public List<Estacionamento> findEstacionamentos(int startingAt, int maxPerPage, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        String q = "SELECT o FROM Estacionamento o";
        if (!filters.isEmpty()) {
            q += " WHERE ";
            for (Map.Entry<String, String> entry : filters.entrySet()) {
                String key;
                key = entry.getKey();
                String value;
                value = entry.getKey();
                q += key + " LIKE :" + value + " AND ";
            }
            q = q.substring(0, q.length() - 4);
        }
        if (sortOrder.equals(SortOrder.ASCENDING)) {
            q += " ORDER BY " + sortField + " ASC";
        } else if (sortOrder.equals(SortOrder.DESCENDING)) {
            q += " ORDER BY " + sortField + " DESC";
        }
        Query query = getSession().createQuery(q);

        if (!filters.isEmpty()) {
            for (Map.Entry<String, String> entry : filters.entrySet()) {
                String key;
                key = entry.getKey();
                String value;
                value = entry.getValue();
                query.setParameter(key, value + "%");
            }
        }
        query.setFirstResult(startingAt);
        query.setMaxResults(maxPerPage);
        return query.list();

    }

    public int countEstacionamentos(Map<String, String> filters) {
        String q = "SELECT COUNT(o) FROM Estacionamento o";
        if (filters != null && !filters.isEmpty()) {
            q += " WHERE ";
            for (Map.Entry<String, String> entry : filters.entrySet()) {
                String key;
                key = entry.getKey();

                String value;
                value = entry.getKey();

                q += key + " LIKE :" + value + " and ";
            }
            q = q.substring(0, q.length() - 4);
        }
        Query query = getSession().createQuery(q);
        if (filters != null && !filters.isEmpty()) {
            for (Map.Entry<String, String> entry : filters.entrySet()) {
                String key;
                key = entry.getKey();

                String value;
                value = entry.getValue();

                query.setParameter(key, value + "%");
            }
        }
        Number result = (Number) query.uniqueResult();

        return result.intValue();
    }
}
Meu LazyDataModel:
public class EstacionamentoModel extends LazyDataModel<Estacionamento> {

    private List<Estacionamento> estacionamentos;

    @Override
    public List<Estacionamento> load(int startingAt, int maxPerPage, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        EstacionamentoDAOImpl estacionamentoDAO = new EstacionamentoDAOImpl();
        estacionamentos = estacionamentoDAO.findEstacionamentos(startingAt, maxPerPage, sortField, sortOrder, filters);

        setRowCount(estacionamentoDAO.countEstacionamentos(filters));

        // set the page dize
        setPageSize(maxPerPage);

        return estacionamentos;
    }

    @Override
    public Object getRowKey(Estacionamento estacionamento) {
        return estacionamento.getEst_id();
    }

    @Override
    public Estacionamento getRowData(String idEst) {
        Long id = Long.valueOf(idEst);

        for (Estacionamento est : estacionamentos) {
            if (id.equals(est.getEst_id())) {
                return est;
            }
        }

        return null;
    }

    @Override
    public void setRowIndex(int rowIndex) {
        /*
         * The following is in ancestor (LazyDataModel):
         * this.rowIndex = rowIndex == -1 ? rowIndex : (rowIndex % pageSize);
         */
        if (rowIndex == -1 || getPageSize() == 0) {
            super.setRowIndex(-1);
        } else {
            super.setRowIndex(rowIndex % getPageSize());
        }
    }
}

2 Respostas

A

Digamos que o nome do seu campo boolean seja “ativo” voceê poderia fazer assim:

na hora de montar a query:

if(key.equals("ativo")){ q += key + " = :" + value + " AND "; }else{ q += key + " LIKE :" + value + " AND "; }

na hora de setar os parametros:

if(key.equals("ativo")){
    query.setParameter(key, Boolean.valueOf(value));
}else{
    query.setParameter(key, value + "%"); 
}

E o filterMatchMode acho que não pode ser pego no LazyDataModel, o jeito seria mesmo verificar os campos como no exemplo que mandei, você poderia até verificar os tipos via reflections também.

F

ayslanms:
Digamos que o nome do seu campo boolean seja “ativo” voceê poderia fazer assim:

na hora de montar a query:

if(key.equals("ativo")){ q += key + " = :" + value + " AND "; }else{ q += key + " LIKE :" + value + " AND "; }

na hora de setar os parametros:

if(key.equals("ativo")){
    query.setParameter(key, Boolean.valueOf(value));
}else{
    query.setParameter(key, value + "%"); 
}

E o filterMatchMode acho que não pode ser pego no LazyDataModel, o jeito seria mesmo verificar os campos como no exemplo que mandei, você poderia até verificar os tipos via reflections também.


Como eu tinha imaginado mesmo, precisa ser feito a “mão”.

Obrigado e tenha um bom dia!

Criado 3 de julho de 2013
Ultima resposta 3 de jul. de 2013
Respostas 2
Participantes 2