Updated April 3, 2023
Introduction to Lazy Loading in Hibernate
Hibernate Lazy Loading is a popular tool of ORM used by developers of JAVA. Hibernate and JPA work along and manages the entity relations. The crucial optimization of database technique is hibernated lazy loading relation, The queries are lessened in the database due to this. Let us see in lazy loading, how we can approach entity relations for one to many, one to one and many to one bidirectional entities. The loading of an entity is done only the first time when you access the entity is called Lazy loading. It saves the pre-filling and preloading costs of all the entities in a huge dataset before while you don’t need them later.
Syntax:
public Entity getEntity() {
if (entity == null) {
entity = loadEntity();
}
return entity;
}
How Lazy Loading in Hibernate Works?
You have entities and there is always a relation between them. Be it one too many or many to one or one to one and other. This hibernate tool allows you to defer the association retrieval which makes you have good control over the strategy of fetching. You define a fetch plan of the global type which can’t be overridden at the time of the query when you use an eager load. Every tool used, the fetching strategy is pretty important. The hibernate the last loading is a commonly used design pattern in programming the computer, which contributes to efficiency if perfectly used. Providing a proxy implementation is an easy and efficient way to use lazy loading in hibernate. A proxy is substituted when hibernating intercepts calls to entity class for it to be derived.
For explicit enabling of lazy loading, we use fetch. Which goes like this:
fetch = FetchType.LAZY
Example
Using hibernate annotations on an association with which you want to lazy load on.
Code #1
package com.fetchsample.example.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "CHILD")
@NamedQuery(name = "Child_By_Name")
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long childId;
@Column(name = "CHILD_NAME")
private String childName;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Toy> toyList = new HashSet<Toy>();
public Long getChildId() {
return childId;
}
public void setChildId(Long childId) {
this.childId = childId;
}
public String getChildName() {
return childName;
}
public void setChildName(String childName) {
this.childName = childName;
}
public Set<Toy> getToyList() {
return toyList;
}
public void addToy(Toy toy) {
toyList.add(toy);
}
}
Code #2
package com.fetchsample.example.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "TOYS")
public class Toy {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "TOY_ID")
private Long toyId;
@Column(name = "TOY_NAME")
private String toyName;
public Long getToyId() {
return toyId;
}
public void setToyId(Long toyId) {
this.toyId = toyId;
}
public String getToyName() {
return toyName;
}
public void setToyName(String toyName) {
this.toyName = toyName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((toyName == null) ? 0 : toyName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Toy other = (Toy) obj;
if (toyName == null) {
if (other.toyName != null)
return false;
} else if (!toyName.equals(other.toyName))
return false;
return true;
}
@Override
public String toString() {
return "Toy [toyId=" + toyId + ", toyName=" + toyName + "]";
}
}
Code #3
package com.fetchsample.example.dao.hibernate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;
public class ChildDAOHibernateImpl extends HibernateDaoSupport implements
ChildDAO {
public void persistChild(Child child) {
getHibernateTemplate().persist(child);
}
public Child getChildByIdWithoutToys(Long childId) {
return getHibernateTemplate().get(Child.class, childId);
}
public Child getChildByIdWithToys(Long childId) {
Child child = getChildByIdWithoutToys(childId);
getHibernateTemplate().initialize(child.getToyList());
return child;
}
public Child getChildByNameWithToys(String childName) {
return (Child) getHibernateTemplate().findByNamedQueryAndNamedParam(
Child.Constants.FIND_CHILD_BY_NAME_QUERY,
Child.Constants.CHILD_NAME_PARAM, childName).get(0);
}
}
The fetch used here is a fetch keyword that initializes the collection of toys and returns the entity of the child that is qualified.
Output:
Conclusion
Considering an online store, a common application used widely on the internet, maintains a product catalog. An entity can manage a series of other entities which can be products in this case. A catalog of such kind should be loaded from the huge database when a customer enters the application. Nobody would want to see the complete catalog so we need to implement lazy loading of hibernate to overcome such problems.
Recommended Articles
This is a guide to Lazy Loading in Hibernate. Here we discuss an introduction to Lazy Loading in Hibernate along with the working and example for better understanding You can also go through our other related articles to learn more –