Difference Query.list() Query.iterate() Hibernate

Difference Query.list() Query.iterate() Hibernate

Query.list() vs Query.iterate()

Note: Before going into the subject Query.list() Query.iterate(), it is advised to know about Eager and Lazy initializations.

Knowledge of queries is very important as they impact the performance else a complex query may take a abnormal long time to execute.

Both methods list() and iterate() are used to retrieve multiple records from the database table. First let us observe signatures of list() and iterate() as defined in Hibernate API.

a) List list() throws HibernateException

Return the query results as a List. If the query contains multiple fields per row, the results are returned in an instance of Object[].

b) Iterator iterate() throws HibernateException

Return the query results as an Iterator. Entities (records) returned are initialized on demand.

Snippet of code for Query.list() and Query.iterate() methods (a full program is available at Hibernate – list() and iterate())

For list()

For iterate()

As it can be observed, the iterate() method avoids a List object.

list() is faster as only one database hit is made.

iterate() makes lot of database hits (one hit for each record or iteration) and there by slower than list(). If the class instances are already available in the session or in second-level cache (perhaps, if iterate() will be faster (else 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 not available in any cache buffer, iterate() will take long time as many database hits are needed even for a simple SQL query.

list() iterate()
1 With one database hit, all the records are loaded For each record, one database hit is made
2 if no cache data is available, this is faster if no chache data is available, this is very slower
3 Eager loading Lazy loading

A full program using Query.list() and Query.iterate() methods is available at Hibernate – list() and iterate().

A similar posting is available on the differences between get() and load().

2 thoughts on “Difference Query.list() Query.iterate() Hibernate

    1. Ashok

      Student s1 = null;
      Object o = session1.get(Student.class, new Integer(101));
      s1 = (Student)o;
      session1.close();
      s1.setDesc(“testing”);
      line–12 session1.update(s1);
      // at line 12 we will get NonUniqueObjectException, but what happend with below code sir?
      Student s1 = null;
      Object o = session1.get(Student.class, new Integer(101));
      s1 = (Student)o;
      session1.clear();
      s1.setDesc(“testing”);
      i thing we wont get any exception, since we are clearing session.
      Please clear me sir.
      line–12 session1.update(s1);

Leave a Reply

Your email address will not be published. Required fields are marked *