user93796
user93796

Reputation: 18399

understanding how objects are fetched in eager(non lazy) load in hibernate

Consider that i have two classes as follows:

class Employee{

  private int empid;
  private string empName;
  //other attributes
  private DepartMent dept;  //note this

}


class Dept{
  private int deptId;
  private String deptName;
  List<Employee>  employees;  //

}

Now using hibernate or any orm if i do a eager fetch for 2 users, both user belonging to same department (by eager fetch i mean when i fetch Emplyee i fetch dept details of the dept to which employee belongs) 1)First for user 1 (of dept1) 2)Then for user 2 (of dept2)

Now as each of employee user1 and user2 is fetched eagerly deptartment details of employee will be fetched 2 time and thus occupy 2 times the memory (for dept details)

IS it the case or thus both user refer to same dept object in memory? Will there be two instances on dept1 in memory?One for dept1 and one for dept 2?

Upvotes: 2

Views: 162

Answers (1)

alwayslearning
alwayslearning

Reputation: 4633

If both Employee rows , emp1 and emp2, point to the same Department row in the database you will have a single representation of each row in memory i.e 2 instances of the 'Employee' class, both pointing to a single instance of the 'Department' class. This is true for objects within a session/context irrespective of whether they are lazy or eager loaded.

If you use a separate context it will maintain it's own set of objects in memory.

Upvotes: 1

Related Questions