Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with Hibernate Lazy Loading

This article will discuss about lazy loading techniques in Java Hibernate.

Today, we are going to discuss about lazy loading technique in Hibernate.

Lazy Loading (Hibernate)

Hibernate defaults to a lazy fetching strategy for all entities and collections. Suppose you have a parent and that parent has a collection of children. Now hibernate can lazy load these children which means that hibernate does not load all the children while loading the parent. Instead it loads children only when it is requested to do so. It prevents a huge load since entity is loaded only once they are required by the program. Hence it increase the performance.

We show this with help of example:

Listing1: Course class

package model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 *
 * @author Anurag
 */
@Entity
public class Course implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "C_ID")
    private Long id;
    private String name;
    private int duration;

    public Course() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Course(String n, int dur) {
        name = n;
        duration = dur;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
 
  • We defined a class Course with fields like id, name, duration.
  • We define the setter and getter function for these
  • We set the id to be auto generated and also we set the name for this column to be C_ID

Listing2: Student class

package model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

/**
 *
 * @author Anurag
 */
@Entity
public class Stu3 implements Serializable {

    private Long id;
    private String name;
    private List<Course> c;

    public Stu3() {
        c = new ArrayList<Course>();
    }

    @Id
    @GeneratedValue
    @Column(name = "STUDENT_ID")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @Fetch(FetchMode.SELECT)
    @JoinTable(name = "STUDENT_Course", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "C_ID")})
    public List<Course> getC() {
        return c;
    }

    public void setC(List<Course> c) {
        this.c = c;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 
  • We made a student class with fields like id ,name. We also made a variable c which can contain course
  • We made setter and getter function for each field
  • We used @Id and @GeneratedValue because we will use the field id as a primary key and its value will be auto generated
  • For implementing many to many mapping we use @ManyToMany(cascade = CascadeType.ALL)
  • @JoinTable(name = "STUDENT_Course", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "C_ID")}) This is used to make a third table named Student_course which will have two columns student_id from the student(stu) class and C_ID from the course class.
  • We used fetch = FetchType.LAZY to tell that the fetching of collection would be lazily done
  • @Fetch(FetchMode.SELECT) is used to tell lazily load all collection and entity.Actually now a separate select query will be made for each retrieval. If we don’t want to make use of lazy load then we may use JOIN which will use only one select query but will load the collections beforehand

Now we define the configuration file:

Listing3: hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateArt</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">csanurag</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="model.Stu3"/>
        <mapping class="model.Course"/>
    </session-factory>
</hibernate-configuration>
 
  • We defined the configuration parameter for the database
  • We also defined the mapping class for both the classes

Now we define the Utility class which will be used to obtain instance of session factory.

Listing4: Utility class

package Main;

/**
 *
 * @author Anurag
 */
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class Utility {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {

            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Lastly we make a class which will make this all work

We make the assumption that there is already records in table

Stu3 table

Rec 1:

  • ID:1
  • Name : Anurag
Course table
  • ID :1
  • Duration : 12
  • Name :J2EE
  • ID :2
  • Duration : 6
  • Name :Hibernate

Student 1 has opted for both of these courses.

Listing4: App2 class

package Main;

/**
 *
 * @author Anurag
 */
import java.util.List;
import model.Course;
import model.Stu3;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class App2 {

    public static void main(String args[]) {

        SessionFactory sf = Utility.getSessionFactory();
        Session s = sf.getCurrentSession();

        Transaction tx = s.beginTransaction();

        Stu3 st1 = (Stu3) s.load(Stu3.class, 1l);

        List<Course> c1 = st1.getC();

        for (int i = 0; i < c1.size(); i++) {
            System.out.println(c1.get(i).getName());
        }
        tx.commit();
    }
}
  • Firstly, We made a session instance with help of session factory object.
  • Now we start the transaction
  • We load the student with id as 1.This will load all information of this student except the courses since courses will be lazily loaded. So till now only student name and id has been loaded
  • Now we use the getter to obtain the courses for this student. And then use the loop to go through individual course and obtain its name. Since we are moving through each record hibernate will now start loading the entity by having a separate query for this.
  • We commit the transaction to make the changes permanent
  • When the program is run then we get both J2EE and hibernate course which are linked with the student id 1

This is all for today’s article. Hope you liked it. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login