Home > hibernate, java, programming > Getting the sorted and paginated contents of a collection in Hibernate

Getting the sorted and paginated contents of a collection in Hibernate

Normally getting the contents of a collection from Hibernate is as easy as retrieving the parent object and calling ‘parent.getCollection()’. But what if you have no interest in the parent and the result set could be huge? I found some help in the hibernate.org ‘Tips and Tricks’ section, but not quite what I was looking for. The solutions given there used filters or pre-defined sorting on the collection.
Sorting
Pagination

The following query retrieves the contents of a collection sorts and paginates them:

public List<Category> getSubCategories(Long categoryId, int start, int size) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String queryString = "select subCategory from SubCategory as subCategory, Category as category where category.id = " + categoryId + " and subCategory in elements(category.subCategories) order by subCategory.name";
        List<Category> subCategories = getList(session.createQuery(queryString), start, size);
        return subCategories;
    }

I’m using Spring, but any way of getting a Hibernate session should work.

Here Category and SubCategory look like:

public class Category {
    protected Long id;

    protected String name;
    protected Set<SubCategory> subCategories = new HashSet<SubCategory>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<SubCategory> getSubCategories() {
        return subCategories;
    }

    public void setSubCategories(Set<SubCategory> subCategories) {
        this.subCategories = subCategories;
    }
}

public class SubCategory {
    protected Long id;
    protected String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

I have intentionally left out the xdoclet tags I use to configure hibernate. The mapping is as simple as it gets.

  1. No comments yet.
  1. No trackbacks yet.