2016-09-22 51 views
2

我正在做一个小型项目,它由一个包含36000条记录的单个表组成,我通过一个DataTable Primefaces展示了这个项目。可以帮助我在LazyDataModel中进行过滤吗?

首先我遇到了速度分页问题,​​这个速度非常慢。

我去了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); 
    } 
} 

最后,LazyDataModel,由ManagedBean叫:

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

我没有使用PrimeFaces几个月,我可能不正确,对不起。你可以搜索这个网站:http://www.primefaces.org/showcase/ui/data/datatable/filter.xhtml。我建议你在DEMO中引用最后一列“价格”,并添加一个filterFunction,以便调试它。 – MageXellos

+4

@MageXellos:如果你做延迟加载,过滤应该在lazyDataModel的加载方法中完成,而不是在filterFunctions中 – Kukeltje

+1

我使用[CriteriaBuilder](http://docs.oracle.com/javaee/7/api/ javax/persistence/criteria/CriteriaBuilder.html)负责过滤。根据字段类型和过滤器值向其添加谓词。 –

回答

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

我,因为我一直在增加调试代码中的注释道歉,但现在是功能齐全。

我重申我的谢意。

+0

出于好奇,这里与PrimeFaces展示相比,在本质上有什么不同?它是反射部分吗? – Kukeltje

+0

确切@Kukeltje,它是Java Reflection的一部分,因为在PrimeFaces中使用“Object.getClass().getField(filterProperty)”,并且getField不允许访问私有成员,但确实允许getDeclaredField。 – gechenique

相关问题