简体   繁体   中英

JSF 2.2 How to sort datatable (show last item created first)

HI I'm trying to sort my datatable so the last item created by the user appers as the first item in the table.

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

Here's my pagination

public abstract class 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;
}

This is how I use the pagination

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

End up doing the sorting with 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM