JSF 2.2如何对数据表进行排序(显示最后创建的项目)

时间:2014-03-02 18:17:26

标签: java jsf jsf-2 datatable

我正在尝试对我的数据表进行排序,以便用户创建的最后一项作为表格中的第一项。

<h:outputText value="#{bean.pagination.pageFirstItem + 1}..#{bean.pagination.pageLastItem + 1}/#{bean.pagination.itemsCount}"/>
<h:commandLink action="#{bean.previous}" 
    value="#{bundle.Previous} #{bean.pagination.pageSize}" 
    rendered="#{bean.pagination.hasPreviousPage}"/>
<h:commandLink action="#{bean.next}" 
    value="#{bundle.Next} #{bean.pagination.pageSize}" 
    rendered="#{bean.pagination.hasNextPage}"/>

<h:dataTable value="#{metadata.placeholders}" var="placeholder">
    <h:column>
    .....
    </h:column>
</h:dataTable>

这是我的分页

公共抽象类PaginationHelper {

private int pageSize;
private int page;

public PaginationHelper(int pageSize) {
    this.pageSize = pageSize;
}

public abstract int getItemsCount();

public abstract DataModel createPageDataModel();

public int getPageFirstItem() {
    return page * pageSize;
}

public int getPageLastItem() {
    int i = getPageFirstItem() + pageSize - 1;
    int count = getItemsCount() - 1;
    if (i > count) {
        i = count;
    }
    if (i < 0) {
        i = 0;
    }
    return i;
}

public boolean isHasNextPage() {
    return (page + 1) * pageSize + 1 <= getItemsCount();
}

public void nextPage() {
    if (isHasNextPage()) {
        page++;
    }
}

public boolean isHasPreviousPage() {
    return page > 0;
}

public void previousPage() {
    if (isHasPreviousPage()) {
        page--;
    }
}

public int getPageSize() {
    return pageSize;
}

这就是我使用分页的方式

public PaginationHelper getPagination() {
    if (pagination == null) {
        pagination = new PaginationHelper(5) {
            @Override
            public int getItemsCount() {
                return getFacade().count();
            }

            @Override
            public DataModel createPageDataModel() {
                return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
            }
        };
    }
    return pagination;
}

1 个答案:

答案 0 :(得分:0)

最终使用JPA进行排序。

    javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<Offer> e = cq.from(Offer.class);
    cq.orderBy(cb.desc(e.get("id")));
    return getEntityManager().createQuery(cq.getResultList();