可以帮我在LazyDataModel中进行过滤吗?

时间:2016-09-22 01:43:33

标签: java jsf primefaces

我正在做一个小项目,它由一个包含36000条记录的表组成,我通过DataTable Primefaces显示这些记录。

首先我遇到了速度分页的问题,这种情况非常缓慢。

我去了Showcase Primefaces并在DataTable中找到了Lazy的例子。

现在分页速度完美但不过滤记录。

我正在开发项目: Netbeans 8.1 64位 JSF 2.2 Primefaces 5.3 Hibernate 4.3.x Informix 7.31 TD6

pojo如下:

package Pojos;
// Generated 18/09/2016 21:10:48 by Hibernate Tools 4.3.1



/**
 * Asociados generated by hbm2java
*/
public class Asociados  implements java.io.Serializable {


 private Integer nroaccionista;
 private Integer idcliente;
 private String razonSocial;
 private Short idlocalidad;
 private Short zona;
 private String calle;
 private String puerta;
 private String localidad;
 private Short estado;

public Asociados() {
}


public Asociados(Integer nroaccionista) {
    this.nroaccionista = nroaccionista;
}
public Asociados(Integer nroaccionista, Integer idcliente, String razonSocial, Short idlocalidad, Short zona, String calle, String puerta, String localidad, Short estado) {
   this.nroaccionista = nroaccionista;
   this.idcliente = idcliente;
   this.razonSocial = razonSocial;
   this.idlocalidad = idlocalidad;
   this.zona = zona;
   this.calle = calle;
   this.puerta = puerta;
   this.localidad = localidad;
   this.estado = estado;
}

public Integer getNroaccionista() {
    return this.nroaccionista;
}

public void setNroaccionista(Integer nroaccionista) {
    this.nroaccionista = nroaccionista;
}
public Integer getIdcliente() {
    return this.idcliente;
}

public void setIdcliente(Integer idcliente) {
    this.idcliente = idcliente;
}
public String getRazonSocial() {
    return this.razonSocial;
}

public void setRazonSocial(String razonSocial) {
    this.razonSocial = razonSocial;
}
public Short getIdlocalidad() {
    return this.idlocalidad;
}

public void setIdlocalidad(Short idlocalidad) {
    this.idlocalidad = idlocalidad;
}
public Short getZona() {
    return this.zona;
}

public void setZona(Short zona) {
    this.zona = zona;
}
public String getCalle() {
    return this.calle;
}

public void setCalle(String calle) {
    this.calle = calle;
}
public String getPuerta() {
    return this.puerta;
}

public void setPuerta(String puerta) {
    this.puerta = puerta;
}
public String getLocalidad() {
    return this.localidad;
}

public void setLocalidad(String localidad) {
    this.localidad = localidad;
}
public Short getEstado() {
    return this.estado;
}

public void setEstado(Short estado) {
    this.estado = estado;
}




}

Pojo映射代码:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD   3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 18/09/2016 21:10:49 by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="Pojos.Asociados" table="asociados" optimistic-lock="version">
        <id name="nroaccionista" type="java.lang.Integer">
            <column name="nroaccionista" />
            <generator class="assigned" />
        </id>
        <property name="idcliente" type="java.lang.Integer">
            <column name="idcliente" />
        </property>
        <property name="razonSocial" type="string">
            <column name="razon_social" length="30" />
        </property>
        <property name="idlocalidad" type="java.lang.Short">
            <column name="idlocalidad" />
        </property>
        <property name="zona" type="java.lang.Short">
            <column name="zona" />
        </property>
        <property name="calle" type="string">
            <column name="calle" length="30" />
        </property>
        <property name="puerta" type="string">
            <column name="puerta" length="10" />
        </property>
        <property name="localidad" type="string">
            <column name="localidad" length="30" />
        </property>
        <property name="estado" type="java.lang.Short">
            <column name="estado" />
        </property>
    </class>
</hibernate-mapping>

DAO:

package Daos;

import Interfaces.InterfazSocios;
import Pojos.Asociados;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;


/**
 *
 * @author Gustavo
 */
public class DaoSocios implements InterfazSocios {

    private List<Asociados> listaSocios;
    private Integer cantidadAsociados;

    @Override
    public List<Asociados> verTodos(Session sesion) throws Exception {
        String hql = "FROM Asociados ORDER BY NroAccionista";
        Query query = sesion.createQuery(hql);
        this.listaSocios = query.list();
        return this.listaSocios;
    }

    public Integer totalDeAsociados(Session sesion) throws Exception {
        String hql = "SELECT COUNT(nroaccionista) FROM Asociados";
        //Query consulta = sesion.createQuery(hql).setCacheable(true);
        this.cantidadAsociados = sesion.createQuery(hql).getMaxResults();
        //this.listaSocios = consulta.list();
        return this.cantidadAsociados;
    }

}

Managed Bean:

package Beans;


import ApoyoBeans.LazyDataModelUsuarios;
import Daos.DaoSocios;
import HibernateUtil.HibernateUtil;
import Pojos.Asociados;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;

/**
 *
 * @author Gustavo
*/
@ManagedBean(name = "mBLazySocios")
@ViewScoped
public class MBLazySocios implements Serializable {

    private LazyDataModel<Asociados> lazyModel;
    private List<Asociados> listaAsociados;
    private Asociados usuarioSeleccionado;

    private Session sesion;
    private Transaction transaccion;

    public MBLazySocios(){

    }

    //@ManagedProperty("#{carService}")
    //private CarService service;

    @PostConstruct
    public void init() {
        try{
            this.sesion = HibernateUtil.getSessionFactory().openSession();
            this.transaccion = this.sesion.beginTransaction();
            DaoSocios dao = new DaoSocios();
            this.listaAsociados = dao.verTodos(this.sesion);
        }catch(Exception e){

        }
        lazyModel = new LazyDataModelUsuarios(this.listaAsociados);
    }

    public LazyDataModel<Asociados> getLazyModel() {
        return lazyModel;
    }

    public Asociados getUsuarioSeleccionado() {
        return usuarioSeleccionado;
    }

    public void setUsuarioSeleccionado(Asociados usuarioSeleccionado) {
        this.usuarioSeleccionado = usuarioSeleccionado;
    }

    //public void setService(CarService service) {
    //    this.service = service;
    //}

    public void onRowSelect(SelectEvent event) {
        FacesMessage msg = new FacesMessage("Asociado Seleccionado",   ((Asociados) event.getObject()).getNroaccionista().toString());
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
}

最后,由ManagedBean调用的LazyDataModel:

package ApoyoBeans;

import Pojos.Asociados;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Gustavo
*/
public class LazyDataModelUsuarios extends LazyDataModel<Asociados> {

    private final List<Asociados> datasource;

    public LazyDataModelUsuarios(List<Asociados> datasource) {
        this.datasource = datasource;
    }

    @Override
    public Asociados getRowData(String rowKey) {
        for(Asociados asoc : datasource) {
            System.out.println(rowKey);
            System.out.println(asoc.getNroaccionista().toString());
            if(asoc.getNroaccionista().toString().equals(rowKey))
                return asoc;
        }

        return null;
    }

    @Override
    public Object getRowKey(Asociados aso) {
        return aso.getNroaccionista().toString();
    }

    @Override
    public List<Asociados> load(int first, int pageSize, String sortField,    SortOrder sortOrder, Map<String,Object> filters) {
        List<Asociados> data = new ArrayList<Asociados>();

        //filter
        for(Asociados asoc : this.datasource) {
            boolean match = true;

            if (filters != null) {
                for (Iterator<String> it = filters.keySet().iterator();  it.hasNext();) {
                    try {
                        String filterProperty = it.next();
                        Object filterValue = filters.get(filterProperty);
                        String fieldValue =  String.valueOf(asoc.getClass().getField(filterProperty).get(asoc));

                        System.out.println("Filtro: " + filterValue.toString());
                        System.out.println("Valor: " + fieldValue);

                        if(filterValue == null ||  fieldValue.startsWith(filterValue.toString())) {
                            match = true;
                    }
                    else {
                            match = false;
                            break;
                        }
                    } catch(Exception e) {
                        match = false;
                    }
                }
            }

            if(match) {
                data.add(asoc);
            }
        }

        //sort
        //if(sortField != null) {
        //    Collections.sort(data, new LazySorter(sortField, sortOrder));
        //}

        //rowCount
        int dataSize = data.size();
        this.setRowCount(dataSize);

        //paginate
        if(dataSize > pageSize) {
            try {
                return data.subList(first, first + pageSize);
            }
            catch(IndexOutOfBoundsException e) {
                return data.subList(first, first + (dataSize % pageSize));
            }
        }
        else {
            return data;
        }
    }
}

啊,以及观点:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:p="http://primefaces.org/ui">

<body>

    <ui:composition template="./plantilla/plantilla.xhtml">

        <ui:define name="top">
            top
        </ui:define>

        <ui:define name="content">
            <h:form id="frmSocios">
                <p:dataTable id="tablaSocios" var="soc" value="#{mBLazySocios.lazyModel}" paginator="true" selection="#{mBLazySocios.usuarioSeleccionado}" rows="25" lazy="true">
                    <p:column headerText="Número Socio" filterBy="#{soc.nroaccionista}" filterMatchMode="contains">
                        <p:outputLabel value="#{soc.nroaccionista}"/>
                    </p:column>
                    <p:column headerText="Número de Cliente">
                        <p:outputLabel value="#{soc.idcliente}"/>
                    </p:column>
                    <p:column headerText="Razón Social" >
                        <p:outputLabel value="#{soc.razonSocial}"/>
                    </p:column>
                    <p:column headerText="Calle">
                        <p:outputLabel value="#{soc.calle}"/>
                    </p:column>
                    <p:column headerText="Puerta">
                        <p:outputLabel value="#{soc.puerta}"/>
                    </p:column>
                    <p:column headerText="Distrito">
                        <p:outputLabel value="#{soc.zona}"/>
                    </p:column>

                </p:dataTable>
            </h:form>
        </ui:define>

        <ui:define name="bottom">
            bottom
        </ui:define>

    </ui:composition>

</body>

展示Primefaces的示例当我将List作为DataSource传递时,我省略了服务类。

我已尽最大努力审查了代码,但在过滤时无法找到错误。

我显示项目运行的屏幕: enter image description here

请注意,第一条记录选择过滤,但不显示任何内容: enter image description here

感谢您给我的任何帮助,感谢您的关注。

1 个答案:

答案 0 :(得分:2)

首先,我要感谢那些关注我办公室的人,特别是那些试图提供解决方案的人。

我希望通过我的解决方案,提出我的问题为“小小的努力”,重新启动并分配正面投票。

在多次调试代码之后,我得出的结论是,在PrimeFaces的例子中,java反射的管理非常糟糕。提出搜索的方式,程序抛出错误来访问POJO的私有成员。

PrimeFaces中提出的这一行(您可以在我的帖子的“LazyDataModelUsuarios”中看到)如下:

String fieldValue = String.valueOf(asoc.getClass().getDeclaredField(filterProperty).get(asoc));

通过实现java反射的正确处理,我的课程如下:

LazyDataModelUsuarios.java:

package ApoyoBeans;

import Pojos.Asociados;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Gustavo
 */
public class LazyDataModelUsuarios extends LazyDataModel<Asociados> {

    private final List<Asociados> datasource;

    public LazyDataModelUsuarios(List<Asociados> datasource) {
        this.datasource = datasource;
    }

    @Override
    public Asociados getRowData(String rowKey) {
        for(Asociados asoc : datasource) {
            if(asoc.getNroaccionista().toString().equals(rowKey)){
                return asoc;
            }
        }

        return null;
    }

    @Override
    public Object getRowKey(Asociados aso) {
        return aso.getNroaccionista().toString();
    }

    @Override
    public List<Asociados> load(int first, int pageSize, String sortField,     SortOrder sortOrder, Map<String,Object> filters) {
        List<Asociados> data = new ArrayList<Asociados>();

        //filter
        System.out.println("Filtros:" + filters);

        for(Asociados asoc : this.datasource) {
            boolean match = true;

            //System.out.println(filters);

            if (filters != null) {
                for (Iterator<String> it = filters.keySet().iterator();   it.hasNext();) {
                    try {
                        String filterProperty = it.next();
                        Object filterValue = filters.get(filterProperty);
                        //String fieldValue =  asoc.getClass().getField(filterProperty).toString();
                        //String fieldValue = asoc.getRazonSocial();
                        //String fieldValue = (String)  asoc.getClass().getDeclaredField(filterProperty).get(asoc);
                        //String fieldValue =  String.valueOf(asoc.getClass().getDeclaredField(filterProperty).get(asoc));



                        Field miembroPrivado =  asoc.getClass().getDeclaredField(filterProperty);
                        miembroPrivado.setAccessible(true);
                        String fieldValue = String.valueOf(miembroPrivado.get(asoc));






                        //System.out.println("Valor de fieldValue:" + fieldValue);


                        if(filterValue == null ||   fieldValue.startsWith(filterValue.toString().toUpperCase())) {
                            //System.out.println("Valor de filterValue.toString" + filterValue.toString());
                            //System.out.println("Valor de fieldValue" + fieldValue);
                            match = true;
                        }
                        else {
                            match = false;
                            break;
                        }
                    } catch(Exception e) {
                        e.printStackTrace();
                        match = false;
                    }
                }
            }

            if(match) {
                data.add(asoc);
            }
        }

        //sort
        //if(sortField != null) {
        //    Collections.sort(data, new LazySorter(sortField, sortOrder));
        //}

        //rowCount
        int dataSize = data.size();
        this.setRowCount(dataSize);

        //paginate
        if(dataSize > pageSize) {
            try {
                return data.subList(first, first + pageSize);
            }
            catch(IndexOutOfBoundsException e) {
                return data.subList(first, first + (dataSize % pageSize));
            }
        }
        else {
            return data;
        }
    }
}

我为调试代码时添加的注释道歉,但现在功能完全正常。

我再次感谢你。

相关问题