Hello Guys! Today I am in your service with my first blog on hibernate lazy and eager loading working.
Hibernate provides two method to fetching the data from the database by using the list() and iterate(), these methods perform lazy and eager loading of data. So today we will learn the internal working of these method. Firstly we will concern on differences of these method.
Difference between list() and iterate() method
|S.No.||List Method||Iterate Method|
|1.||Select the required records at a time.||Select the required records from the table one after another.|
|2.||Generates the single SQL select query.||Generates the multiple SQL select query. Example – The first select query returns the identity value and remaining select query return the records.|
|3.||Perform the immediate initialization of the objects with the selected
records. (Eager Loading)
|Perform the lazy loading.|
|4.||For example – Selecting the 4 records from the table will generate the single SQL select query.||For example – Selecting the 4 records will generate the 5 SQL select query.|
Iterator Example – Iterator it = employee.iterate();
* Execute the select query on each Id value and get the one record internally. It perform the following task.
1. Execute the select query to get the Id of all the records.
2. Create the Employee objects by populating the Id into it.
3. Adding the employee object into the collection (ArrayList).
4. Invokes the it.iterator() method to get and return the iterator object.
Note – ( When the getter method in the while loop is invoked then the select query will be executed to get the complete record. )
List Example – List l = employee.list();
1. Execute the select query to get all the records.
2. Create the object of arraylist.
3. Creating the Employee object and populating the record values into it, then added employee objects into the arraylist.
4. Returns the ArrayList Object.
Hibernate Program -
// import statements
Session session = factory.openSessioin();
Query query = session.createQuery("from Employee as eb");
List l = query.list();
// Make Hibernate software to execute HQL query process the list data soruce.
for(int i=0; i<l.size(); i++)
Employee eb = (Employee)l.get();
// print eb.getEid()
// print eb.getFname()
// print ("Object class name is " + l.getClass());
// In case of iterator.
Iterator it = query.iterate();
//Execute select query to get all the Id's.
Employee emp = (Employee)it.next();
// print emp.getEid()
// print emp.getFname()
Hope this help to understand the internal working of list() and iterate() method .