Hibernate - Interview Questions and Answers on Lazy Loading / Lazy Initialization / Lazy Fetching

Q1.  What is Lazy Loading / Lazy Initialization in Hibernate ?

Ans. It's a feature to lazily initialize dependencies , relationship and associations from the Database. Any related references marked as @OneToMany or @ManyToMany are loaded lazily i.e when they are accessed and not when the parent is loaded.

Q2.  How to do Eager loading in Hibernate ?

Ans. Using 

lazy = false in hibernate config file 

or

@Basic(fetch=FetchType.EAGER) at the mapping

Q3.  What are the ways to avoid LazyInitializationException ?

Ans. 1. Set lazy=false in the hibernate config file.

2. Set @Basic(fetch=FetchType.EAGER) at the mapping.

3. Make sure that we are accessing the dependent objects before closing the session.

4. Using Fetch Join in HQL.

5. Adding a filter for session management and keep the session open till request completion.

Q4.  After which Hibernate version , related Entities are initialized lazily ?

Ans. After Hibernate 3.0