【问题标题】:Can help me with filtering in LazyDataModel?可以帮助我在 LazyDataModel 中进行过滤吗?
【发布时间】:2016-09-22 01:43:32
【问题描述】:

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

首先我遇到了速度分页的问题,速度慢得令人发指。

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

现在分页速度可以完美运行,但不能过滤记录。

我正在开发这个项目: Netbeans 8.1 64 位 JSF 2.2 Primefaces 5.3 休眠 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;
    }

}

托管 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 传递时,我避免了服务类。

我已经最大限度地审查了代码,但过滤时找不到错误。

我显示了正在运行的项目的屏幕:

请注意,第一条记录选择过滤,但什么也不显示:

如果您能给我任何帮助,我将不胜感激,感谢您的关注。

【问题讨论】:

  • 我已经有几个月没有使用 PrimeFaces 了,我可能不正确,抱歉。你可以搜索这个网站:primefaces.org/showcase/ui/data/datatable/filter.xhtml。建议你参考DEMO的最后一列“价格”,加上一个filterFunction,方便调试。
  • @MageXellos:如果你做延迟加载,过滤应该在lazyDataModel的load方法中进行,而不是在filterFunctions中进行
  • 我使用CriteriaBuilder 来处理过滤。根据字段类型和过滤器值添加谓词。
  • 嗨@JasperdeVries,你有例子吗?
  • @gechenique 我将在下周创建一个答案

标签: java jsf primefaces


【解决方案1】:

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

我希望通过我的解决方案,将我的问题提出为“一点点努力”,revea 并给予肯定的投票。

在多次调试代码后,我得出的结论是,在 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;
        }
    }
}

对于我为调试代码而添加的 cmets,我深表歉意,但现在已完全正常运行。

再次感谢。

【讨论】:

  • 出于好奇,这里与 PrimeFaces Showcase 相比有什么根本不同?是反射部分吗?
  • 完全是@Kukeltje,它是 Java 反射的一部分,因为在 PrimeFaces 中使用“Object.getClass ().getField (filterProperty)”并且 getField 不允许访问私有成员,但允许 getDeclaredField。
猜你喜欢
  • 2018-09-28
  • 1970-01-01
  • 2021-06-24
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 2019-09-05
  • 1970-01-01
  • 2017-06-22
相关资源
最近更新 更多