Hibernate - Getting records in sorted order and hibernate pagination.

Hibernate has inbuilt API for ordering and retrieving records in pages.We can use Criteria API to get the result from database instead of Using query or load/get. The things those are applied in SQL queires, same are applied here with the help of Criteria API. You can provide selection conditions to criteria object. You can add order and pagination of records. Here is the simple method for example.

 public List<Contact> getAll(int pageNumber , int pageSize,boolean isAsc,String sortingBy) {
        List<Contact> l=null;
        Criteria c=currentSession().createCriteria(Contact.class);
        if(isAsc){
            c.addOrder(Order.asc(sortingBy));
        }else{
            c.addOrder(Order.desc(sortingBy));
        }
        c.setFirstResult((pageNumber - 1) * pageSize);
        c.setMaxResults(pageSize);
        
        l=c.list();
        return l;
 }

No comments:

Popular Posts