Flushing in NHibernate

NHibernate has a two layer caching system. The first layer is always active and designed to optimize performance. The second cache is optional and pluggable. You can choose your own provider. The second layer cache is, for example, a good place to cache reference data that doesn’t change so much. If used correctly, the caching mechanism can improve performance significantly.

When changes are made to the persistent objects, they are not immediately propagated to the database. NHibernate stores them in the first layer cache. In this way many changes can be combined into fewer database requests. For example, if a property is updated several times during a session, NHibernate only needs to execute one single SQL update. But when are the changes synchronized with the database? NHibernate calls the synchronization with the database for flushing, and it occurs when:

1) When a transaction commits to make the changes durable.

2) Before a query executes, if the first layer cache contains modified data that affects the result of the query.

3) When the application explicitly calls Flush().

It is also possible to change the default behavior by changing the FlusMode property in the session. As I understand this is not recommended.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.