You should use a ScrollableResults, as described here :
http://blog.hibernate.org/cgi-bin/blosx ... 2004/08/26
Code:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
ScrollableResults customers = session.getNamedQuery("GetCustomers")
.scroll(ScrollMode.FORWARD_ONLY);
int count=0;
while ( customers.next() ) {
Customer customer = (Customer) customers.get(0);
//do what you want here...
if ( ++count % 20 == 0 ) {
//flush a batch of updates and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
I guess that even if you're using NHibernate, you can use a close way for doing this.