Both of the methods list() and iterate() are used to fetch multiple records from the database table. Let´s focus first on the signature of these methods in Query interface.
1. List list() throws HibernateException: Returns the query results as a java.util.List. If the query contains multiple fields or columns per row, the results are returned in an instance of Object[].
2. Iterator iterate() throws HibernateException: Returns the query results as an Iterator. Entities (records) are initialized on demand.
Example of list():
----------------------------
Query q = s.createQuery("FROM Student");
List list = q.list();
Iterator it = list.iterator();
while(it.hasNext())
{
Student std = (Student)it.next();
System.out.println(std.getSid() + " " + std.getSname() + " " + std.getSmarks()+ " " + std.getSjoindate());
}
Or you can iterate elements from above list using advance for loop.
for(Student s:list){
System.out.println(s.getSid() + " " + s.getSname() + " " + s.getSmarks()+ " " + s.getSjoindate());
}
Example of iterate():
---------------------------------
Query q = s.createQuery("FROM Student");
Iterator it = q.iterate();
while(it.hasNext())
{
Student std = (Student)it.next();
System.out.println(std.getSid() + " " + std.getSname() + " " + std.getSmarks()+ " " + std.getSjoindate());
}
As it can be seen, the iterate() method avoids a List object.
list() is faster than iterate() as only one database hit is made.
iterate() makes lot of database hits (one hit for each record or iteration) and that´s why it is slower than list().
If the database records are already available in the primary level cache (Session) or Secondary level cache (SessionFactory), iterate() method will be faster.
And if the database records are not available in any cache buffer, iterate() will take long time as many database hits are needed even for a simple SQL query.
Let´ see the key difference between list() and iterate():
--------------------------------------------------------------------------
1. By list with one database hit, all the records are loaded in a java.util.List, while by iterate, one database hit is made for each record.
2. if no cache data is available, list is faster and iterate is very slower.
3. It uses Eager loading and it uses Lazy loading.
5