Lazy Loading in Hibernate

Facebooktwitterredditpinterestlinkedinmailby feather

Lazy loading is a fetching technique used for all the entities in Hibernate. It decides whether to load a child class object while loading the parent class object. When we use association mapping in Hibernate, it is required to define the fetching technique. The main purpose of lazy loading is to fetch the needed objects from the database.

For example, we have a parent class, and that parent has a collection of child classes. Now, Hibernate can use lazy loading, which means it will load only the required classes, not all classes. It prevents a huge load since the entity is loaded only once when necessary. Lazy loading improves performance by avoiding unnecessary computation and reduce memory requirements.

Lazy loading can be used with all types of Hibernate mapping, i.e., one-to-one, one-to-many, many-to-one, and many-to-many.

Syntax of Lazy Loading

To enable Lazy loading, we use the following annotation parameter:

Following code is the syntax of lazy loading:

Example of Lazy Loading

  1. Create all POJO classes

In this step, we are going to develop persistent classes, i.e., Categories.java and Items.java.

Categories.java

Items.java

  • Create the configuration file

In this step, we are going to create the configuration class (hibernate.cfg.xml) which contains the information of POJO class and the database.

hibernate.cfg.xml

<pre class="wp-block-preformatted"        update  org.hibernate.dialect.MySQL5Dialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/test root</property>                        root</property> 
  • Create the main class that stores the object of the persistent class

In this step, we are going to create a class which consists of main() method, and stores the objects of POJO classes.

App.java

  • Output
Lazy Loading in Hibernate
  • Database tables

categories table

Lazy Loading in Hibernate 1

items table

Lazy Loading in Hibernate 2

cate_items table

Lazy Loading in Hibernate 3
Facebooktwitterredditpinterestlinkedinmailby feather