Primefaces Lazy Filtering Issue

时间:2012-12-09 18:41:06

标签: hibernate datatable primefaces lazy-loading filtering

我正在尝试在我的应用程序中实现延迟加载,但是我的过滤问题。此时排序工作正常。使用延迟过滤,数据表最初从表中加载24个记录的正确计数,但它反复重复第1和第2个记录。非常感谢任何帮助。

这是我的ScreenshotListProducer类代码:

    @ManagedBean
    @RequestScoped
    public class ScreenshotListProducer implements Serializable  {
       private static final long serialVersionUID = 1L;
       @Inject
       private EntityManager em;

       private List<Screenshot> screenshots;

       private LazyDataModel<Screenshot> lazyModel = null;

       private int pageSize = 5;

       public void setPageSize(int pageSize) {
           this.pageSize = pageSize;
       }

       public int getPageSize() {
           return pageSize;
       }

       @Produces
       @Named
       public List<Screenshot> getScreenshots() {
          System.out.println("************* getting screenshots list **************");
          return screenshots;
       }

       @PostConstruct
       public void LoadData() {
         lazyModel = new LazyDataModel<Screenshot>() {
        private static final long serialVersionUID = 1L;

      @Override
      public List<Screenshot> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) { 
           int start = first;
                  int end = first + pageSize;
                  if (sortField == null) {
                     sortField = "time";
                  }

                 try {
               CriteriaBuilder cb = em.getCriteriaBuilder();
               CriteriaQuery<Screenshot> criteria = cb.createQuery(Screenshot.class);
               Root<Screenshot> screenshot = criteria.from(Screenshot.class);

               // sorting
               if (sortOrder.equals(SortOrder.ASCENDING))
                {
                  criteria.select(screenshot).orderBy(cb.asc(screenshot.get(sortField)));
                }
                else if (sortOrder.equals(SortOrder.DESCENDING))
                {
                   criteria.select(screenshot).orderBy(cb.desc(screenshot.get(sortField)));
                }

               // From
               Root<Screenshot> from = criteria.from(Screenshot.class);

               List<Predicate> predicates = new ArrayList<Predicate>();

               if (filters != null) {
                  // filters
                  for(Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
                     String filterProperty = it.next(); // table column name = field name
                     System.out.println("filterProperty is: " + filterProperty);

                     String filterValue = filters.get(filterProperty);
                     System.out.println("filterValue is: " + filterValue);

                     Expression<String> literal = cb.literal((String)filterValue);
                     predicates.add(cb.like(from.<String>get(filterProperty), literal));
                  }
                  criteria.where(predicates.toArray(new Predicate[predicates.size()]));
               }

               TypedQuery<Screenshot> s = em.createQuery(criteria);
               s.setMaxResults(end - start);
               s.setFirstResult(start);

               screenshots = s.getResultList();

            } catch (NullPointerException e) {
               e.printStackTrace();
            }

                          return screenshots;
           }

         };

   lazyModel.setRowCount(24);
   lazyModel.setPageSize(pageSize);

   if (lazyModel.getRowIndex() == -1 || lazyModel.getPageSize() == 0) {
            lazyModel.setRowIndex(-1);
       }
       else
           lazyModel.setRowIndex(lazyModel.getRowIndex() % lazyModel.getPageSize());
       }

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

这是我的截图类:

@Entity
@XmlRootElement
@Table(name="Test2012", uniqueConstraints = @UniqueConstraint(columnNames = "id"))
public class Screenshot implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    @Column(name = "id", columnDefinition="INT")
    private Long id;

    private Timestamp time;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Timestamp getTime() {
        return time;
    }

    public void setTime(Timestamp time) {
        this.time = time;
    }   
}

这是我的xhtml代码:

<p:dataTable id="table1" var="scrshot" rowKey="#{scrshot.id}" value="#{screenshotListProducer.lazyModel}" paginator="true" rows="7" paginatorPosition="bottom"
             paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" 
             rowsPerPageTemplate="7,20,50,100" widgetVar="dataTable" currentPageReportTemplate="(Number of Records: {totalRecords})"
             emptyMessage="No screenshot data found with given criteria" lazy="true" scrollable="true" draggableColumns="true" scrollHeight="217" style="width: 100%;"> 
      <f:facet name="header"> 
      </f:facet>
      <p:column selectionMode="multiple"/> 
      <p:column id="time" headerText="Time" sortBy="#{scrshot.time}" filterBy="#{scrshot.time}" filterMatchMode="startsWith"> 
        <h:outputText value="#{scrshot.time}"/> 
      </p:column>   
      <p:column id="id" headerText="ID" sortBy="#{scrshot.id}" filterBy="#{scrshot.id}" filterOptions="#{scrshot.id}" filterMatchMode="exact"> 
        <h:outputText value="#{scrshot.id}"/> 
      </p:column> 
</p:dataTable>

Primefaces 3.3.1 Mojarra 2.1.5 JBoss AS 7.1.0.Final

2 个答案:

答案 0 :(得分:1)

几句话:

  • 您正在使用@RequestScoped。我似乎记得过滤/排序和请求范围的问题(不确定这是问题)。请改为@ViewScoped或更高的范围。
  • 不要在顶层(支持bean)中使用数据访问(例如,与EntityManager等数据库相关的内容)。将其分为2层或3层:GUI - (业务逻辑) - 数据访问。
  • 您发布的ScreenshotListProducer课程有一个混乱的缩进,使其难以阅读。它似乎也没有正确关闭(缺少“}”)。
  • JSF中的globalFilter似乎没有连接到数据表。 (我可能在这里错了。)
  • 您似乎正在创建3个过滤器,2个列过滤器和1个全局过滤器,哪一个会导致问题?下次更具体一点; - )
  • 删除不相关的代码并缩小代码,以制作一个演示问题的简短示例。示例:modeOptionsformatOptions似乎没有被使用,只会影响问题的可读性。

答案 1 :(得分:0)

感谢您的投入。我的加入问题是我的'From'定义。我把它拿出来并在我的过滤器中使用我原来的“屏幕截图”,它现在可以正常过滤。