Hibernate – Lazy Collection
Last Updated :
07 Jun, 2023
Hibernate is a powerful open-source framework for Java that provides an object-relational mapping solution. It simplifies the process of working with databases which allow developers to map Java objects with the data present in the database tables. Hibernate handles the data persistence which allows developers to focus more on object-oriented aspects rather than focusing on low-level database operations.
What is the Lazy Collection in Hibernate?
In Hibernate, Lazy Collection refers to a collection of entities that are not being loaded from the database until they are explicitly needed. Hibernate uses lazy loading for collections to optimize performance and reduce memory consumption. Lazy loading is a principle of on-demand fetching of data where the associated entities are being loaded from the database only when they are necessary. This behavior prevents Hibernate to avoid fetching unnecessary data when dealing with large collections or complex object graphs.
Example of Lazy Collection
Example 1:
Java
package com.example.java_test_application;
@Entity
public class Employee {
@Id
private Long empId;
@Column (name = "empName" )
private String empName;
@OneToMany (mappedBy = "employee" , fetch = FetchType.LAZY)
private List<Tasks> tasks;
}
|
In the above example tasks property is a list of task entities. mappedBy attribute is used for one-to-many annotation which tells Hibernate that task property is the inverse side of one-to-many relationships. This means that the Hibernate will not load tasks property when the Employee entity is loaded. Instead of tasks property will only be loaded when it is accessed for the first time. If we have to call the first task of an employee we have to simply call the below code.
Java
Employee employee = (Employee) session.get(Employee. class , 1L);
Tasks task = employee.getTasks().get( 0 )
|
Similarly for getting the second task for an employee we have to simply change the index for the get Tasks method from 0 to 1.
Example 2:
Java
package com.example.java_test_application;
@Entity
public class Mobile {
@Id
private Long mobileId;
@Column (name = "mobileName" )
private String mobileName;
@OneToOne (fetch = FetchType.LAZY)
private MobileFeatures mobileFeatures;
}
|
In the above example mobile feature property is a reference to Mobile Features entity. The fetch = FetchType.Lazy attribute on One to one annotation tells Hibernate to load mobile features property lazily. This means that mobile features will only be loaded when it is accessed for the first time. To load the mobile features for the mobile we have to call the below code snippet.
Java
Mobile mobile = (Mobile) session.get(Mobile. class ,1L);
MobileFeatures mobileFeatures = mobile.getFeatures();
|
With the help of the above code we can get the features of a mobile phone.
Share your thoughts in the comments
Please Login to comment...