0

我正在尝试在我的应用程序中实现延迟加载,但我的过滤存在问题。此时排序工作正常。使用延迟过滤,数据表最初会从表中加载正确的计数,即 24 条记录,但它会一遍又一遍地重复第一条和第二条记录。任何帮助是极大的赞赏。

这是我的 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

4

2 回答 2

1

几点说明:

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

感谢您的输入。我的加入问题与我的“来自”定义有关。我把它拿出来并在我的过滤器中使用了我原来的“屏幕截图”,它现在可以正确过滤了。

于 2012-12-12T16:14:28.453 回答