Spring pagination support for Hiberate

May 18, 2006

As I have said before I love Spring and Hibernate; however, there is no Spring support for Hibernate’s pagination API. Why am I am not sure. Maybe they are supporting it now but heres what I did. First I made and abstract object I called ‘Page’. I also have a Solr subclass of this object but I will cover that later.

public abstract class Page {

    public List results;
    private int pageNumber;
    private int resultsPerPage;
    private int totalCount;
    private String queryString;
    private Integer totalPages = null;

        Getters and setters


public class PageHibernate extends Page implements HibernateCallback {

    public PageHibernate() { }

    public PageHibernate(String queryString, int page, int resultsPerPage) {

    public final Object doInHibernate(Session session)
            throws HibernateException {

        Query query = session.createQuery(this.getQueryString());
        query.setFirstResult((getPageNumber() – 1) * getResultsPerPage());

        return this.results = query.list();

Since Spring abstracts your Hibernate interaction with HibernateDaoSupport you dont have to write straight criteria calls to Hibernate if you dont want to. Spring does create simple implementation to allow to write straight HQL and many other functions but not pagination. Rather than tackle this problem at this angle I decided to make the abstract class ‘Page’ that you see above for all my data stores. Anyway, here’s how easy it is to then hit the database with this object properly constructed and have it returned ready for use.

public Page getPageOfThings(int page, int resultsPerPage, String orderBy) {

    PageHibernate newPage = new PageHibernate(
            ”FROM Thing”, page, resultsPerPage);


    List count = getHibernateTemplate().find(“SELECT count(*) FROM Thing”);


    return newPage;


Categories: Software

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2005-2011 John Clarke Mills

Wordpress theme is open source and available on github.