Lazy Loading
How It Works
@OneToMany(mappedBy = "author", fetch = FetchType.LAZY)
private List<Book> books; // Proxy - not loaded yet
// Access triggers SQL:
author.getBooks().size(); // NOW query executes
LazyInitializationException
Accessing lazy collection after session closes = exception.
Solutions
// 1. @Transactional
@Transactional(readOnly = true)
public Author getWithBooks(Long id) { ... }
// 2. JOIN FETCH
@Query("SELECT a FROM Author a JOIN FETCH a.books WHERE a.id = :id")
Author findByIdWithBooks(Long id);
// 3. EntityGraph
@EntityGraph(attributePaths = {"books"})
Optional<Author> findById(Long id);
Best Practices
Key Principles
- Follow SOLID principles
- Write clean, readable code
- Test thoroughly
- Document decisions
- Monitor in production
Implementation
- Start simple, refactor as needed
- Use established patterns
- Consider trade-offs
- Review with peers
Continuous Improvement
- Learn from incidents
- Update documentation
- Share knowledge
- Mentor others
Key Points
- Understanding Lazy Loading is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Lazy Loading in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Lazy Loading implementation
// Key aspects: validation, error handling, logging, testing
public class LazyLoading {
// Production-ready implementation
}Identify and handle edge cases for Lazy Loading. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Lazy Loading. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. LazyInitializationException cause?
2. JOIN FETCH loads in?
3. What is the primary purpose of Lazy Loading?
4. What is a common mistake when implementing Lazy Loading?
Flashcards
Question
LazyInitializationException?
Click to reveal answer
Answer
Accessing lazy collection after session closed
Question
JOIN FETCH?
Click to reveal answer
Answer
Single query for parent + children
Question
What is Lazy Loading?
Click to reveal answer
Answer
Lazy Loading is a key concept in backend development.
Question
When to use Lazy Loading?
Click to reveal answer
Answer
Use Lazy Loading when building production systems that require reliability, scalability, and maintainability.
Question
Lazy Loading best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Lazy: loads on access
- 2.LazyInitializationException: session closed
- 3.Fix: @Transactional, JOIN FETCH, EntityGraph
Interview Tips
- •Handle LazyInitializationException
- •Know lazy vs eager
Cheat Sheet
Lazy Loading
- Loads on access (default for collections)
- Exception: session closed
- Fix: @Transactional, JOIN FETCH