Skip to content

Instantly share code, notes, and snippets.

@malalanayake
Last active August 29, 2015 13:57
Show Gist options
  • Save malalanayake/9532896 to your computer and use it in GitHub Desktop.
Save malalanayake/9532896 to your computer and use it in GitHub Desktop.
Pagination with Hibernate Criteria in Java
public List<Admin> getAllAdminsWithPagination(int page, int recordePerPage) {
session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tr = null;
try {
tr = session.beginTransaction();
Criteria cr = session.createCriteria(Admin.class);
cr.setFirstResult((page - 1) * recordePerPage);
cr.setMaxResults(recordePerPage);
List<Admin> adminAll = cr.list();
tr.commit();
if (adminAll.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Admin users are not exist");
}
return null;
} else {
if (log.isDebugEnabled()) {
log.debug("Found " + adminAll.size() + " Admin users");
}
return adminAll;
}
} catch (RuntimeException ex) {
log.error(ex);
if (tr != null) {
tr.rollback(); // roll back the transaction due to runtime error
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment