Lazy Loading - bobocode-breskul/bibernate GitHub Wiki
Lazy Loading
Overview
Lazy Loading is an optimization technique used in ORM frameworks, including Bibernate, to enhance application performance and resource utilization. It delays the loading of associated entities until they are explicitly accessed by the application. This approach contrasts with eager loading, where related entities are loaded immediately with the main entity, regardless of whether they are needed.
How It Works
- When an entity is retrieved from the database, its associations (e.g., one-to-many or many-to-one relationships) are not immediately loaded.
- Instead, proxy objects or placeholders are created for these associated entities.
- The actual database query to load the associated entities is executed only when the application accesses these objects for the first time.
- This deferred loading reduces the initial load time and memory usage, as unnecessary data is not loaded.
Benefits
- Performance Improvement: Reduces the initial loading time of entities, especially when the associated data is not needed immediately or might not be used at all.
- Reduced Memory Footprint: Decreases the amount of memory required by an application by avoiding the loading of unnecessary entities.
- Flexible Resource Management: Allows for more controlled resource usage by fetching data on-demand, which can be particularly beneficial in scenarios with limited resources or large datasets.
Considerations
- N+1 Selects Problem: Improper use of lazy loading can lead to the N+1 selects problem, where an application makes one query to load the main entity and then an additional query for each associated entity. Careful design and querying strategies, such as batch fetching, can mitigate this issue.
- Transaction Boundaries: Lazy loading requires an open session or connection to the database. Accessing lazily-loaded properties outside of active session boundaries can result in exceptions (e.g., LazyInitializationException in Hibernate).