EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Lazy Loading in Hibernate

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Hibernate Tutorial » Lazy Loading in Hibernate

Lazy Loading in Hibernate

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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:

Lazy Loading in Hibernate - 1

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 –

  1. Spring Hibernate Integration
  2. Hibernate Interview Questions
  3. Hibernate Session
  4. Caching in Hibernate

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Hibernate Tutorial
  • Basic
    • What is Hibernate
    • What is Java Hibernate
    • Hibernate Versions
    • Hibernate Architecture
    • Hibernate Framework
    • Hibernate Tools
    • Hibernate Annotations
    • Hibernate Mapping
    • Hibernate Many to One
    • Hibernate Many to Many
    • Hibernate Dialect
    • Hibernate Session
    • Hibernate SessionFactory
    • Lazy Loading in Hibernate
    • Hibernate Criteria
    • Hibernate Persist
    • Hibernate EntityManager
    • Caching in Hibernate
    • Cascade in Hibernate
    • Hibernate Generator
    • Hibernate Validator
    • Spring Hibernate Integration
    • Hibernate Query Language
    • Hibernate Named Query
    • Hibernate Interview Questions
    • HQL
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - All in One Software Development Bundle (600+ Courses, 50+ projects) Learn More