@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