Lazy Loading in Hibernate with Examples
Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used
Lazy fetching 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 actully 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.
Employee mapped to Employee object and contains set of Address objects. Parent Class : Employee class, Child class : Address Class
public class Employee {
private Set address = new HashSet(); // contains set of child Address objects
public Set getAddress () {
return address;
}
public void setAddresss(Set address) {
this. address = address;
}
}
In the Employee.hbm.xml file
In the above configuration. If lazy="false" : - when you load the Employee object that time child object Address is also loaded and set to setAddresss() method. If you call employee.getAdress() then loaded data returns.No fresh database call.
If lazy="true" :- This the default configuration. If you don?t mention then hibernate consider lazy=true. when you load the Employee object that time child object Adress is not loaded. You need extra call to data base to get address objects. If you call employee.getAdress() then that time database query fires and return results. Fresh database call.
Important points about Lazy Loading
@OneToMany and @ManyToMany associations are defaulted to LAZY loading.
@OneToOne and @ManyToOne are defaulted to EAGER loading.
Lazy loading allows you to defer the association retrieval or to have a better control over the fetching strategy.
Loading data you need currently instead of loading whole bunch of data at once which you won't use now. Thereby making application load time faster than usual.
Hiberante supports the feature of lazy initialization for both entities and collections. Hibernate engine loads only those objects that we are querying for does not other entites or collections.
Advantages of Lazy loading
Lazy loading allows you to defer the association retrieval or to have a better control over the fetching strategy.
When you use EAGER loading, you define a global fetch plan which cannot be overridden at query time, meaning you are limited to a decision you took while designing your entity model. The EAGER fetching is a code smell, because the fetching strategy is a query-time policy and it might differ from a business use case to another.
The fetching strategy is a very important aspect, as too much EAGER fetching can cause serious performance related issues.
We have example
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee {
@Id@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "mobile")
private String mobile;
@ManyToMany(targetEntity = Address.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)@JoinTable(name = "employee_address", joinColumns = @JoinColumn(name = "emp_id_fk", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "addr_id_fk", referencedColumnName = "id"))
private Set address;
/*
@Getters
@Setters
*/
}
We have Address.java
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity@Table(name = "Address")
public class Address implements Serializable
{
@Id@GeneratedValue@Column(name = "id")
private long id;
@Column(name = "street", nullable = false, length = 250)
private String street;
@Column(name = "city", nullable = false, length = 50)
private String city;
@Column(name = "state", nullable = false, length = 50)
private String state;
@Column(name = "zip", nullable = false, length = 10)
private String zipcode;
@ManyToMany(targetEntity = Employee.class, mappedBy = "address", fetch = FetchType.LAZY)
private Set employee;
//@Getters
//@Setters
}
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class MyApp
{
public static void main( String[] args )
{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session= factory.openSession();
Employee emp = new Employee();
emp.setId(1);
emp.setName("Bala");
emp.setMobile("9999999990");
Address address1 = new Address("F C Road", "Pune", "MH", "411005");
Address address2 = new Address("J M Road", "Pune", "MH", "411004");
emp.setAddress(address1);
emp.setAddress(address2);
Transaction ts = session.beginTransaction();
session.save(emp);
ts.commit();
System.out.println("saved successfully!!!!");
session.close();
}
}
In the above example we have
//Following code loads only a single category from the database:
Employee emp = (Employee)session.get(Employee.class,new Integer(1));
However, if all Addresses of the Employee are accessed, and lazy loading is in effect, the Addresses are pulled from the database as needed. For instance, in the following snippet, the associated address objects will be loaded since it is explicitly referenced in second line.
//Following code loads only a single category from the database
Employee emp = (Employee)session.get(Employee.class,new Integer(1));
@OneToMany( mappedBy = "Employee", fetch = FetchType.LAZY )
private Set<Address>addresses;
//This code will fetch all products for Employee 1 from database - "NOW"
Set<Address>= emp.getAddress();
//this is a lazy loading.
How to enable lazy loading in hibernate
@OneToMany( mappedBy = "Employee", fetch = FetchType.LAZY )
private Set<Address> addresses;
In this article, we have seen Lazy Loading in Hibernate with Examples .
0 Comments
Post a Comment