org.hibernate.LazyInitializationException
The LazyInitializationException
occurs when attempting to access un-fetched data (represented by a proxy) from the database in a detached manner (outside the Hibernate session scope). This is tied to Hibernate’s default fetching policies for entity relationships.
EAGER
(fetches associated entity immediately).LAZY
(defers fetching the collection until accessed).EAGER
(fetches associated entity immediately).LAZY
(defers fetching the collection until accessed).LAZY
Category
or Restaurant
), Hibernate does not automatically fetch the many side (e.g., BlogPost
or FoodItem
).
SELECT
query is fired only on the categories
or restaurants
table, not on blog_posts
or food_items
.LazyInitializationException
Occur?BlogPost
list in Category
or FoodItem
list in Restaurant
) outside the session scope.category.getBlogPosts()
).load
(or getReference
): Returns a proxy that triggers the exception if accessed outside the session.List<BlogPost>
or List<FoodItem>
) substitutes un-fetched data, and accessing it outside the session throws the exception.EAGER
Configuration:
@OneToMany(mappedBy = "chosenCategory", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private List<BlogPost> posts = new ArrayList<>();
Effect: Hibernate fetches the BlogPost
list whenever a Category
is loaded.