Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate StateLessSession vs DefaultReadOnly

Tags:

nhibernate

In NHibernate, what is the difference between:

using(var session = _sessionFactory.OpenStatelessSession()) {
    //Do Work
}

and

using(var session = _sessionFactory.OpenSession()) {
    session.DefaultReadOnly = true;
    //Do Work
    session.DefaultReadOnly = false;
}

I only want some entities in certain contexts to be Stateless and others not. I can either use two sessions (one statefull and one stateless) or wrap the queries I want to be stateless in to DefaultReadOnly-calls.

like image 413
Lodewijk Avatar asked Aug 06 '26 08:08

Lodewijk


1 Answers

setting DefaultReadOnly to true just means NHibernate won't track the entities properties and won't update the entity on the database (at least sometimes). It will still keep the entity in its session cache. A stateless session doesn't keep track of its entities in the first place, saving some memory.

If you're only concerned about readonly, you could probably go with a single session and DefaultReadOnly = true. But if you want NHibernate to not use its session cache when loading an entity (for instance, to get the current data from the database, not the data in the session cache from 5 minutes ago), you'd be better served with a stateless session.

like image 60
Dirk Trilsbeek Avatar answered Aug 10 '26 11:08

Dirk Trilsbeek