Loading...
56

I'm getting this error when trying to access a collection after fetching an entity:

__CODEBLOCK0

My entities:
CODEBLOCK1__

I understand it's because the session is closed, but what's the best way to fix this in Spring Boot?

asked 6 days ago

Log in to add a comment.

1 Answer

48

There are several ways to fix LazyInitializationException. Here are the best approaches:

Solution 1: Use DTOs with JOIN FETCH (Recommended)
__CODEBLOCK0

*Solution 2: Use @EntityGraph
_CODE_BLOCK_1_

Solution 3: Use Open Session in View (NOT recommended for production)
_CODE_BLOCK_2_

Solution 4: Use DTO Projection (Best for APIs)
_CODE_BLOCK_3_

Solution 5: Change to EAGER (Generally NOT recommended)
_CODE_BLOCK_4_

Recommendation:*

    1. Use JOIN FETCH for web transactions
    2. Use DTO projections for API responses
    3. Disable </strong><em>CODE</em>BLOCK<em>5</em>__ in production
    4. Never use EAGER fetching on collections

answered 5 days ago
Log in to answer this question.
Question Stats
Asked: 6 days ago
Views: 1.8k
Active: 1 hour ago
Related Tags