Thursday, October 6, 2016

Eager and Lazy Loading in Hibernate

Eager Loading - Means loading an object with its entire dataset in one go. This creates a performance hit since everything gets loaded as soon as we make the object, even if we dont want to use it.

Lazy Loading - Create the object but don't load the dataset. Load them only when they are required. Basically here we make a proxy object and operate on it.
We load this proxy object with the necessary data from dataset only when they are requested.

Use lazy loading when we are not sure what data we will need at runtime and eager loading when we know what data we want at runtime everytime we load the object.

To save memory, Lazy loading is generally used for one to many and many to many relationships. For one to one, generally Eager is used.


Memorize this :)
OneToMany:    LAZY
ManyToOne:    EAGER
ManyToMany: LAZY
OneToOne:       EAGER
Columns :          EAGER


Example->
public class Organization 
{
 private String employeeID;
 private String name;
 private String address;
 private List<Employees> employees;

 // setters and getters
}

Now when you load a Organization from the database, Hibernate loads its employeeID, name, and address fields for you. But you have two options for employees; to load it together with the rest of the fields (Eager Fetch) or to load it on-demand (Lazy Fetch) when you call the Organization's getListOfEmployees() method.

@ElementCollection(fetch=FetchType.LAZY)   OR @ElementCollection(fetch=FetchType.EAGER) // use either one of the two
@JoinTable(name="EMP_DTLS",joinColumns=@JoinColumn(name="EMP_ID"))

private Collection<Employees> listOfEmployees = new ArrayList<Employees>();
    
public Collection<Employees> getListOfEmployees() {
        return listOfEmployees;
}


No comments:

Post a Comment

Home