Lazy relationships load on access when a suitable persistence context exists. Define what data a response needs before serialization.
Before you start
You should know Java classes, dependency injection and basic HTTP requests. Identify where a call crosses a framework-managed boundary. The snippets illustrate a focused mechanism; database configuration, application wiring and authentication must be supplied by the surrounding application when applicable.
The practical goal is to reason through this situation: An endpoint fetches the required association or projects fields within the service boundary. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Define response fields
Know which associations the endpoint needs before serialization begins.
Step 2: Fetch within the boundary
Use an intentional fetch strategy or projection while the required persistence context is available.
Step 3: Return an explicit DTO
Avoid exposing entity traversal as an uncontrolled serialization-time query plan.
Worked scenario
An endpoint fetches the required association or projects fields within the service boundary.
An invoice response needs customer name but not the entire customer graph. Load the necessary data and map it before leaving the service boundary. Serializing a lazy association afterward can fail or trigger additional queries depending on session policy; neither should be an accidental part of the API contract.
Common mistake
Accessing a lazy relationship after the context closes can fail or trigger uncontrolled loading policies.
Verify the behavior
Inspect query count and response serialization with the context closed.
Interview exercise
Design a predictable response.
Answer and reasoning
Map to a response DTO using an explicit fetch strategy and measure query count before returning it.
Continue learning
Compare the scenario with the Spring Boot interview questions and test your understanding with the Spring Boot MCQs. For terminology and implementation details, consult the reference material.