Hibernate lazy

In this section, you will learn about lazy loading in Hibernate.

Hibernate lazy

Hibernate lazy

In this section, you will learn about lazy loading in Hibernate.

In Hibernate, lazy load means loading child objects while loading the Parent Object. This setting must be done in Hibernate mapping XML / Parent file of the parent class.

  • If lazy="true" means not to load child objects while loading the Parent Object.

  • If lazy="false" means load child objects while loading the Parent Object.

  • By default, the lazy loading of the child objects is true.

Example

Consider the below One-to-Many mapping shown by the figure :

Many people living in the same street and the city  have common address except the room no. / flat no. In the above mapping, we are showing that many employee table's  records have common adress_id .

The XML mapping file of both table is given below :

Employee.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="net.roseindia">

<class name="Employee" table="employee">
<id name="employeeId" column="employee_id">
<generator class="native" />
</id>

<property name="firstname" column="firstname"/>
<property name="lastname" column="lastname" />
<property name="cellphone" column="cell_phone" />

<many-to-one name="address" class="net.roseindia.Address" fetch="select">
<column name="address_id" not-null="true" />
</many-to-one>

</class>
</hibernate-mapping>

Address.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="net.roseindia">
<class name="Address" table="address">
<id name="addressId" column="address_id">
<generator class="native" />
</id>
<property name="street" column="street"/>
<property name="city" column="city"/>
<property name="state" column="state"/>
<property name="country" column="country"/>
<set name="employees" table="employee" inverse="false" lazy="true" fetch="select">
<key>
<column name="address_id" not-null="true" />
</key>
<one-to-many class="net.roseindia.Employee" />
</set>
</class>
</hibernate-mapping>

In the context of above configuration :

  • If lazy="true", means don't load child object(employee) while loading parent object(address). If you try to access employee(child) records then it will make a fresh call to database table  to load child object.

  • If lazy="false", means load child object(employee) while loading parent object(address).  If you try to access employee(child) records, then already loaded child object is returned. No fresh call to database table needed.

  • By default, the lazy loading of the child objects(employee) is true.