tags:

views:

38

answers:

2

I have a hibernate query which returns 10s of thousands of object results. Is it possible to cycle through chunks of the query rather than handling the entire query at once?

Sample code:

Query q = session.createQuery("FROM Class");


List<Class> classList = (List<Class>) q.list();

Thanks

+1  A: 

Use query.setMaxResults(int) and query.setFirstResult(int) to page through the query.

Usually you'd write a method that displays page x of the result size where y is the number of items per page:

public List<Thingy> showThingies(int itemsPerPage, int pageOffest){
    // ..
    query.setMaxResults(itemsPerPage);
    query.setFirstResult(itemsPerPage * pageOffset);
    // ..
}
seanizer
+1  A: 

You could use the ScrollableResults from hibernate

Something like:

ScrollableResults results = session.createCriteria(Project.class)
            .add(Restrictions.eq("projectType", Constants.REINDEX.PROJECT_TYPE))
            .setFetchSize(10)
            .scroll(ScrollMode.FORWARD_ONLY);

while (results.next()) {
        project = (Project) results.get(0);

If you are scrolling through a huge ammount of entities you should probably also clear your session from while to while, else you could run out of memory.

More information is to be found in the documentation 10.4.1.6. Scrollable iteration and as they wrote it, you should use pagination if you don't want your connection to stay open.

HeDinges