Saturday, May 19, 2012

Fetch Type - Lazy vs. Eager Loading in EJB 3.0

Fetch Type - Lazy vs. Eager Loading in EJB 3.0:

The fetch type is used to specify the data-fetching strategy that a persistence provider uses to fetch data from the database. FetchType is used on the @Basicannotation, @LOB annotation, and relationship annotations such as OneToMany, ManyToMany, ManyToOne, and OneToOne. The default for fetchTypeis EAGER, except for a ManyToMany and a OneToMany relationship, for which the default is LAZY. A fetchType of EAGER means that a persistence provider will load the attribute of an entity along with the entity, whereas a fetchType of LAZY is a hint to the provider that the attribute need not be fetched along with the entity, or we can say that In eager loading we will fetch all the values from the Persistent storage and cache it. It will make serious performance issues. There we use lazy loading to avoid that.

Keep in mind that a FetchType of EAGER is a requirement on the persistence provider, whereas a fetchType of LAZY is only a hint. So even though you may specify the fetchType to be LAZY, the persistence provider may choose to load the attribute eagerly.
A FetchType of lazy benefits Large Objects and Relationships in which the attributes are not accessed immediately when the entity is loaded.The attributes are loaded whenever required.

Example:

@Entity
public class Order {
@OneToMany(fetchType=FetchType.EAGER, ...)
public Collection<OrderLineItem> getLineItems(){
return lineItems;
}
}

@Entity
public class Order {
@OneToMany(fetchType=FetchType.LAZY, ...)
public Collection<OrderLineItem> getLineItems(){
return lineItems;
}
}


No comments:

Post a Comment