Examples of Lazy Loading in Hibernate

Examples of Lazy Loading in Hibernate
Techiio-author
Written by Sagar RabidasFebruary 15, 2022
7 min read
Hibernate
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

Let's start the discussion with Lazy Loading in Hibernate.

Lazy Loading in Hibernate:-

Hibernate lazy loading is a famous device of ORM utilized by developers of java. Hibernate and JPA work along and control the entity family members. The essential optimization of database technique is hibernated lazy loading relation, the queries are lessened inside the database due to this. Let us see in lazy loading, how we can method entity members of the family for one to many, one to at least one, and lots of to at least one bidirectional entities. The loading of an entity is completed simplest the primary time while you get admission to the entity is referred to as lazy loading. It saves the pre-filling and preloading fees of all of the entities in a massive dataset earlier than you don’t want them later.

Syntax:

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

How Lazy Loading in Hibernate Works:-

You've got entities and there may be usually a relation among them. Be it one too many or many to 1 or one to at least one and other. This hibernate tool permits you to defer the association retrieval which makes you have true control over the method of fetching. You define a fetch plan of the worldwide kind that couldn't be overridden at the time of the question whilst you use an eager load. For each tool used, the fetching strategy is quite vital. The hibernate the remaining loading is a typically used layout sample in programming the pc, which contributes to efficiency if flawlessly used. Imparting a proxy implementation is a smooth and efficient manner to use lazy loading in hibernate. A proxy is substituted when hibernating intercepts calls to entity elegance for it to be derived.

For explicit enabling of lazy loading, we use fetch. Which goes like this:

fetch = FetchType.LAZY

Examples:-

Use 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);
}
}

Hibernate
Lazy Loading
LazyLoadingHibernate
Java
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+9 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software91
DevOps48
Frontend Development24
Backend Development20
Server Administration17
Linux Administration28
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance