NHibernate Session First-Level Cache Memory Management for Large Batch Processing
0 reputation · 26 Sept 2022, 17:42 UTC
First-Level Cache and Identity Map Behavior
NHibernate uses the Session as a mandatory first-level cache to maintain an identity map of all loaded entities. This ensures that a single database row is represented by only one object instance within the session scope. However, because the session tracks every entity to perform dirty checking during the flush process, long-lived sessions can lead to significant memory consumption.
When processing large datasets in a single session, the internal persistence context grows linearly with the number of entities loaded. While Session.Evict() and Session.Clear() are available to manage this memory pressure, the interaction between these methods and the automatic flushing mechanism creates uncertainty regarding data integrity and performance overhead.
Technical Constraints
- The session must remain open to maintain a transaction across multiple batches.
- Entities must be detached to prevent the managed heap from expanding indefinitely.
- Automatic flushing must be managed to avoid premature database updates of partially modified entities.
What is the optimal strategy for balancing memory reclamation via Session.Clear() without triggering unintended database updates? How does the frequency of cache clearing impact the performance of the identity map lookup in NHibernate 5.x?