Saturday, August 20, 2011

JPA: Difference between LAZY and EAGER fetching strategies.

Lets say that we have a Department and an Employee relationship in our data model. The department could have attributes such as, an id, a name, a description, and a collection of employees that belong to that department. This will be a one-to-many relationship from the Department's view (a department can have many employees), and a many-to-one from the Employee's.  Lets, illustrate this with the following example.

@Entity
public class Department {
        @Id
private Long id;
private String name;
private String description;
        @OneToMany(mappedBy = "department")
private List<Employee> employees;
       ....
       public List<Employee> getEmployees() {
          return empoloyees;
       }
      ....
}

@Entity
public class Employee {
        @Id
private Long id;
private String firstName;
private String lastName;
@ManyToOne()
@JoinColumn(name = "employee_id")
private Department deparment;
       ...
}

Now, if we need to load (fetch) a department from the database, Hibernate/JPA could load these properties in two different ways: Lazy and Eager. Lazy loading practically means that Hibernate/JPA will only load the id, name and description, but  if we need to load the employees, we'll request them on-demand by using the getEmployees() assessor method of the Department's class. If the department has many employees, then it might not be very efficient to load all of them when they are not needed. To specified Lazy loading  we'll modified our OneToMany annotation as follows. 
@OneToMany( fetch = FetchType.LAZY) 

With Eager loading, Hibernate/JPA loads all the properties's data along with all the employees associated with a department. To specified Eager loading  we'll modified our OneToMany annotation as follows. 
@OneToMany( fetch = FetchType.EAGER)

Note:  The default fetching strategies: 
EAGER: @OneToOne, @ManyToOne. 
LAZY: @OneToMany, @ManyToMany




3 comments:

  1. Good post... just to add
    that in entities, the property values are loaded eagerly and the Collections get loaded lazily.

    ReplyDelete