It sounds like you are trying to work around the problem that your session lifetime is wrong. A session is designed to be used for a single unit of work. Instead of clearing the session in this way to carry on using it, you should be flushing it and starting again with a new one. If you are using this to speed the application up due to caching, I suggest you look at second-level caching in NHibernate, which operates at the SessionFactory
rather than Session
level.
If you have a long-running editing process, with a large batched save at the end, then in my view you should be working with the objects disconnected. So you use one session to load the objects, and any of their related objects, edit with them outside the context of a session, then at the end of the process, reattach these objects to a new session using SaveOrUpdate
and then flush that session. This sort of approach works best if you are using offline otimistic locking for your concurrency approach, using for example a SQL Server timestamp
column or the Oracle ORA_SCN
virtual column as your version. If an object has changed underneath you, then the update will fail with a StaleObjectStateException
.
But YMMV, and I'd need to know more about your application to say anything more specific than this.