Skip to content
Branch: master
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
src/main
README.md
hibernate spring boot join fetch.png
pom.xml

README.md

How To Avoid LazyInitializationException Via JOIN FETCH

See also:
- LEFT JOIN FETCH
- JOIN FETCH And DTOs
- JOIN VS. JOIN FETCH

Description: Typically, when we get a LazyInitializationException we tend to modify the relationship fetching type from LAZY to EAGER. That is bad! This is a code smell. Best way to avoid this exception is to rely on JOIN FETCH (if you plan to modify the fetched entities) or JOIN + DTOs (if the fetched data is only read). JOIN FETCH allows associations or collections of values to be initialized along with their parent objects using a single SELECT. This application is a JOIN FETCH example with entities. But, with some constraints, JOIN FETCH can be used with DTOs as well. An example is available here.

Key points:
- define two related entities (e.g., Author and Book in a one-to-many lazy bidirectional relationship)
- write a JPQL JOIN FETCH to fetch an author including his books
- write a JPQL JOIN FETCH to fetch a book including its author

Output example:

You can’t perform that action at this time.