[Example-Lab] Eager and Lazy Fetch Types in Hibernate 5

We will see a simple example to illustrate the LAZY and EAGER Fetch in Hibernate.

We will have a User class that refer to an Address class, and a test class. If you are not following the tutorials in order, refer to the article http://javajee.com/your-first-hibernate-program-using-hibernate-43 for the basic setup including hibernate configuration file and refer to http://javajee.com/embedding-value-types-within-an-entity-class-in-hibernate-43 for the Address class.


Case 1: Default Behaviour (FetchType.LAZY)

Initially the user class will use an empty @ElementCollection annotation to refer to the embedded collection.


User Class

The User class will look as:

package com.javajee.hiberex.dto;


import java.util.ArrayList;

import java.util.Collection;

import javax.persistence.ElementCollection;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.Id;



public class User {



  int id;

  private String name;


  private Collection<Address> addresses = new ArrayList<Address>();

  //Getters and setters not shown, you can refer to other tutorials or generate it in eclipse.



Address Class

We will use the same Address class from http://javajee.com/example-lab-embedding-value-types-within-an-entity-cl....


Test Class

In the test class, after retrieving user, we will close session and then try to print the values of the embedded collection.

The test class will look as below:

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import com.javajee.hiberex.dto.Address;

import com.javajee.hiberex.dto.User;


public class UserTest {


  public static void main(String[] args) {


    User u = new User();




    Address addr = new Address();





    Configuration configuration = new Configuration();


    ServiceRegistry serviceRegistry = StandardServiceRegistryBuilder()


    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    Session session = sessionFactory.openSession();





    u = null;

    session = sessionFactory.openSession();


    u = (User) session.get(User.class, 1);



    for(Address add : u.getAddresses()){






Verifying the results

If you execute this code, you will get this exception:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection…

This is because when you call session.get for user, only user fields (except the address list collection) is retrieved.

We are then trying to print the address details after session.close, but after session.close there is no session available to retrieve the address details lazily and hence it throws an exception.

If you change the @ElementCollection annotation to @ElementCollection (fetch=FetchType.LAZY), the behavior will be same and you will still get org.hibernate.LazyInitializationException.

This is because FetchType.LAZY is the default.


Case 2: FetchType.EAGER

Now change the @ElementCollection annotation to @ElementCollection (fetch=FetchType.EAGER) in User class as:

@ElementCollection (fetch=FetchType.EAGER)

private Collection<Address> addresses = new ArrayList<Address>();

Execute the same TestUser class and you will get a successful response this time.

This is because in EAGER initialization, you retrieve the collection during session.get for user and not retrieved after session.close.

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) ArrayLists (1) Arrays (2) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (53) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (8) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (12) Java Programmer 2 (8) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) resources (1) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)