Question

I am trying to learn Hibernate, I came through hibernate lazy initialization . I have a few clarifications regarding the lazy initialization.

First of all, What is so called Lazy initialization, what does it do? Secondly, when should i go for it ? Next, I came across, in blogs saying, using it improves performance and I just need to know how. Then, Are there any cons of using it? Can any one help me understanding this lazy initialization?

Was it helpful?

Solution

Lazy fetching (or initialization) is the opposite of eager fetching. Lazy fetching, the default in hibernate, means that when a record is loaded from the database, the one-to-many relationship child rows are not loaded. E.g.

@Entity
@Table(name = "COMPANY")
public class Company {
...
@OneToMany(fetch = FetchType.LAZY)
private Set<Employee> employees = new HashSet<Employee>();

requesting a company record will not return (set) Employees, who will have to be requested in another query.

Advantages

  • performance. Employees are only loaded when needed (and requested). Benefit on CPU, memory, bandwidth... (both Java side and SQL server side).

Drawbacks

  • when Employees are also needed, a separated query has to be performed.

Note that the query on Employees has to be performed during the same session (or the famous LazyInitializationException will be unwelcome).

This page holds interesting information.

OTHER TIPS

Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actually called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.Examples lazy=true (default) Address child of User class can be made lazy if it is not required frequently. lazy=false But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Lazy initialization means lazy loading.

In very few words-

initialize an object when you first need it, it gives you high performance as unnecessary objects are not loaded."

e.g.- suppose you needed to have a record which has a join of several tables. If you fetched it all at once it would take longer than if you would fetch say only the main table. Using lazy-loading the rest of the information will be fetched only if it is needed. So it is actually efficient-loading in certain scenarios.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top