So I created an OrderList class which could hold a sorted series of order clauses.
Code:
public class OrderList {
private List<Order> orders;
public OrderList add(Order order) {
if (orders == null) {
orders = new ArrayList<Order>();
}
orders.add(order);
return this;
}
public List<Order> getOrders() {
return orders;
}
}
I can now create the orders list like:
Code:
OrderList orderList = new OrderList().add(Order.asc("firstname")).add(Order.asc("lastname")).add(Order.asc("email"));
And pass it to the generic Dao method like:
Page<UserAccount> page = getPage(pageNumber, pageSize, criteria, orderList);
The generic Dao looks like:
Code:
public Page<T> getPage(int pageNumber, int pageSize, Criteria criteria, Projection projection, OrderList orderList) {
int totalSize = 0;
if (pageSize > 0) {
criteria.setProjection(Projections.rowCount());
// TODO Why is uniqueResult returning a Long and setFirstResult requiring an int ?
totalSize = ((Long) criteria.uniqueResult()).intValue();
int startIndex = Page.getStartIndex(pageNumber, pageSize, totalSize);
criteria.setFirstResult(startIndex);
criteria.setMaxResults(pageSize);
}
if (projection != null) {
criteria.setProjection(projection);
} else {
// Remove the count project
criteria.setProjection(null);
// Specify the main class as being the projection to avoid JOINed projections
criteria.setResultTransformer(Criteria.ROOT_ENTITY);
}
if (orderList != null) {
for(Order order : orderList.getOrders()) {
criteria.addOrder(order);
}
}
List<T> list = criteria.list();
return new Page<T>(pageNumber, pageSize, totalSize, list);
}
In case there is a specific projection, then it is passed as well to the generic Dao method.
Some additional methods are provided for the different cases of using a projection and / or some order clause:
Code:
@Override
public Page<T> getPage(int pageNumber, int pageSize, Criteria criteria) {
return getPage(pageNumber, pageSize, criteria, null, null);
}
@Override
public Page<T> getPage(int pageNumber, int pageSize, Criteria criteria, Projection projection) {
return getPage(pageNumber, pageSize, criteria, projection, null);
}
@Override
public Page<T> getPage(int pageNumber, int pageSize, Criteria criteria, OrderList orderList) {
return getPage(pageNumber, pageSize, criteria, null, orderList);
}