Hibernate – Lazy Loading

An object may contents reference of other object and those other object may have reference of other objects, just like a exponential chain or graph. When we load an object with entire object graph created all at once in the first attempt, it fires the construction of lot of objects in branch which gives a performance hit and slows the main object creation.
So to avoid this delay, “Lazy Loading” concept is introduced.
In lazy load the main object is loaded only with bare required properties like id and few data types, however the composition and other reference object are not loaded at the very first time. So the object is created quickly and becomes available for use in the application. When ever the child or composite objects are called on the main object reference, their are created and supplied on the need basis.

Hence the main object is loaded at first time without its children, and children are loaded lazily on the need basis.

The pattern is like this:

public Entity getEntity() {
if (entity == null) {
entity = loadEntity();
}
return entity;
}

This saves the cost of preloading/prefilling all the entities in a large dataset beforehand while you after all actually don’t need all of them.
In Hibernate, you can configure to lazily load a collection of child entities. The actual lazy loading is then done inside the methods of the PersistentSet which Hibernate uses “under the hoods” to assign the collection of entities as Set.

E.g.

public class Parent {
private Set<Child> children;

public Set<Child> getChildren() {
return children;
}
}

.

public void doSomething() {
Set<Child> children = parent.getChildren(); // Still contains nothing.

// Whenever you call one of the following (indirectly),
// Hibernate will start to actually load and fill the set.
children.size();
children.iterator();
}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s