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
and/or DTOs. 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