What is Lazy Loading in Hibernate ?
Lazy loading determines whether child objects should be loaded when the parent object is retrieved from the database. In Hibernate XML mapping, you can configure this behavior using the lazy="true" attribute. When using annotations, you can specify the fetch strategy with FetchType.LAZY.
With lazy loading, the child objects are not loaded immediately when the parent object is fetched. Instead, they are loaded only when they are accessed in the application, for example, by calling the getChild() method on the parent object. At that point, Hibernate executes an additional SQL query to retrieve the child objects.
In some scenarios, however, you may want the child objects to be loaded along with the parent object. In such cases, you can disable lazy loading by setting lazy="false" in the XML mapping or by using FetchType.EAGER with annotations. Hibernate will then fetch both the parent and its associated child objects in the same retrieval process.
The default fetch type depends on the type of the relationship:
@ManyToOneand@OneToOnehave a default fetch type ofFetchType.EAGER.@OneToManyand@ManyToManyhave a default fetch type ofFetchType.LAZY.
Example:--
Employee.java
@Entity @Table (name="employee") public class Employee { @Id @Column(name="id") private int id; @Column(name="emp_name") private String name; @OneToMany(cascade=CascadeType.ALL, FetchType.LAZY) @JoinColumn(name="address_id") private Set<Address> address; // setters and getters }
In the above example, Employee and Address entity have the One to Many relationship. The default fetch type of One to Many relationship is LAZY.
Address.java,
@Entity @Table (name="address") public class Address { @Id @Column(name="id") private int id; @Column(name="address") private String address; // setters and getters }
Main Class,
HibernateMain.java,
package com.adnblog; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.adnblog.Employee; public class HibernateMain { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); Transaction txn = session.beginTransaction(); Employee emp = session.get(Employee.class, 1); //check the below output System.out.println("Name:--"+emp.getName());
Set<Address> addressSet = emp.getAddress(); tx.commit(); sessionFactory.close(); } }
Output :--
select employee0_.id as id1_0_0_, employee0_.name as name1_0_0_, employee0_.address as address2_0_0_ from Employee employee0_ where employee0_.id=? Name:-- Kiran select employee0_.id as id1_0_0_,employee0_.name as name1_0_0_, employee1_.id as id2_0_0, employee1_.address as address2_0_0_ from Employee employee0_ join Address employee1_ where employee0_.id=?
In the above example, Hibernate does not load the
Address entity when the parent object is initially fetched. Instead, it returns a proxy object for the Address association. The Address table is queried only when the getAddress() method is invoked for the first time. At that point, Hibernate executes an additional SQL query to load the actual Address entity. Hibernate does not support lazy initialization for detached objects. If you attempt to access a lazily loaded association after the Hibernate session has been closed, Hibernate throws a LazyInitializationException because it can no longer retrieve the required data from the database.
Summary:--
FetchType.LAZY is the recommended choice because it loads associated entities only when they are actually needed.FetchType.EAGER instructs Hibernate to fetch the associated entities along with the parent entity during the initial query. This can be efficient when the related entities are always required, as all the necessary data is retrieved in a single database query. However, in many scenarios, it results in unnecessary overhead by loading entities that are not used, which can negatively impact application performance.
FetchType.LAZY delays the loading of associated entities until they are explicitly accessed in the application. This approach improves performance by avoiding unnecessary data retrieval. However, when a lazy association is accessed, Hibernate executes an additional SQL query to load the required data. Therefore, it is important to use lazy loading carefully to avoid issues such as the N+1 query problem.
Thank you for visiting the blog!
No comments:
Post a Comment