Use Hibernate Paging when processing lots of objects
At work right now I have been trying to solve an OutOfMemoryException in a Java web application. The app exposes a bunch of web services. All of which can end up processing a large collection of objects returned via Hibernate. All of which can also keep a Hibernate session opened for a very long time.
So far, the solution we have found is to use paging along with releasing the session before doing another Hibernate query. We do the query, get back a collection of objects and iterate over that collection, processing each one in turn. Then, when we are done, we close that session, open a new one and get another collection of objects.
Hibernate makes this very easy to do:
public Collection find(int page, String hsql) {
getSession.close();
getSession();
int page_size = 25;
query=session.createQuery(hsql);
return query.setFirstResult(page * page_size)
.setMaxResults(page_size).list();
}
I have not supplied implementations for getSession since this depends on how you are working with Hibernate (i.e., Spring or HibernateUtil class).