Skip to content

Instantly share code, notes, and snippets.

@brunoadacosta
Created April 2, 2012 12:50
Show Gist options
  • Save brunoadacosta/2283220 to your computer and use it in GitHub Desktop.
Save brunoadacosta/2283220 to your computer and use it in GitHub Desktop.
Paginação Hibernate
public class Pagination<T> {
private final long totalRecords;
private final List<T> results;
public Pagination(long totalRecords, List<T> results) {
this.totalRecords = totalRecords;
this.results = results;
}
public List<T> getResults() {
return results;
}
public long getTotalRecords() {
return totalRecords;
}
}
public class PaginationParams {
private Integer page;
private Integer rows;
private String orderBy;
public PaginationParams() {
}
public PaginationParams(Integer page, Integer rows, String orderBy) {
this.setPage(page);
this.rows = rows;
this.orderBy = orderBy;
}
public Integer getPage() {
return (page + 1);
}
public Integer getRows() {
return rows;
}
public Integer getFirstResults() {
return page * rows;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public Order getOrderByCriteria() {
return getOrdersParams().get(0);
}
public List<Order> getListOfOrderByCriteria() {
return getOrdersParams();
}
private List<Order> getOrdersParams() {
String[] params = getOrderBy().split(" ");
String[] properties = params[0].split(",");
String order = params[1];
List<Order> orders = new ArrayList<Order>();
for (String property : properties) {
orders.add(order.equalsIgnoreCase("asc") ? Order.asc(property) : Order.desc(property));
}
return orders;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public void setPage(Integer page) {
this.page = page <= 0 ? 0 : --page;
}
}
public class Paginator<T> {
private final Query query;
private final Criteria criteria;
public Paginator(Query query) {
this.query = query;
this.criteria = null;
}
public Paginator(Criteria criteria) {
this.criteria = criteria;
this.query = null;
}
public final Pagination<T> paginate(PaginationParams paginationParams) {
final long totalRecords = totalRecords();
List<T> results = generateList(paginationParams);
return new Pagination<T>(totalRecords, results);
}
@SuppressWarnings("unchecked")
private List<T> generateList(PaginationParams paginationParams) {
Integer firstResults = paginationParams.getFirstResults();
Integer rows = paginationParams.getRows();
return query == null ? criteria.setFirstResult(firstResults).setMaxResults(rows).list() : query.setFirstResult(firstResults)
.setMaxResults(rows).list();
}
private long totalRecords() {
if (query != null) {
return query.list().size();
}
if (criteria != null) {
Long count = (Long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult();
criteria.setProjection(null);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return count;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment