Thursday, February 28, 2008

NHibernate flush

Note: This discussion is only limited to first level cache provided at ISession level in NHibernate.
Flush(): Unlike its name is suggesting, purpose of Flush() is not to clear cache. It synchronizes the cached objects with the database.In short, you cache and database gets in sync with each other. All that you retrieve using Load(), Get() and List() is entitled to stay in cache. When you do 'save', 'update' or 'delete', operations of NHibernate, not all operations are immediately performed to database. It is when you use 'flush' of NHibernate session, all 'yet to be done' change of database are done. Note that 'flush' is transaction safe. Means, all the operation done in a transaction by 'flush' can be rolled back with other things of transaction.

When to use flush? When you are interested in dirty reading of data, Flush() refreshes your modified data into database (and obviously, does “undo” if the Nhibernate transaction is rolled back) .
What to do to clear cache? Use “Evict” to clear individual object or collection of objects, Isession.Clear() removes all objects.


s3kvir pascon said...

Does ISession.Clear() removes all objects from all cache or only from first level cache (and leaves collections)?

Yogee said...

I believe Session.Clear() 'evicts' all in Session level cache objects.

Yogee said...

Ok.. googled and found this: chapter 19.3.

It says,
we sessionFactory.evict is for second-level cache.