What is the difference between StatelessSession
and Session
in NHibernate?

- 22,228
- 29
- 98
- 151
-
possible duplicate of [difference between sessionfactory.openSession() and sessionfactory.openStatelessSession()?](http://stackoverflow.com/questions/5496995/difference-between-sessionfactory-opensession-and-sessionfactory-openstatelesss) – Péter Török May 24 '11 at 08:00
-
answer [here](http://stackoverflow.com/questions/2679636/nhibernate-isession-vs-istatelesssession) – Renatas M. May 24 '11 at 08:03
-
Possible duplicate of [NHibernate - ISession vs. IStatelessSession](https://stackoverflow.com/questions/2679636/nhibernate-isession-vs-istatelesssession) – Owen Pauling Jul 26 '18 at 08:29
2 Answers
Stateless session is not tracking entities that are retrieved. For example for regular ISession
following code:
var session = sessionFactory.OpenSession()
using(var transaction = session.BeginTransaction()){
var user = session.Get<User>(1);
user.Name = "changed name";
transaction.Commit();
}
will result in update in DB. This tracking consumes memory and makes ISession
performance to degrade over time since amount of tracked entities is growing.
The same code with IStatelessSession
won't do anything. Stateless sessions are used when you need to load lots of data and perform some batching operations. It can be used to work with large data sets in a more "ado.net" style.

- 15,046
- 12
- 60
- 89
-
14This answer needs more detail about `StatelessSession`. How about a code example where you DO update the database with a `StatelessSession`? – Jess Jan 30 '15 at 14:00
Session in the NHibernate caches all the inserted data in the session level cache.
using (var session = sessionFact.OpenSession())
{
using (var trans = session.BeginTransaction())
{
for (int = 0; i < 500000; i++)
{
Student st = new Student(
{
ID = 1,
FirstName = "Zia",
LastName = "Qammar"
});
session.Save(st);
}
trans.Commit();
}
}
above code throw an "OutOfMemoryException" exception while inserting 50,000 student in the database. The other approach that NHibernate provides is StatelessSession which persist the data in database in detached objects.
using (var session = sessionFact.OpenStatelessSession())
{
using (var trans = session.BeginTransaction())
{
for (int = 0; i < 500000; i++)
{
Student st = new Student(
{
ID = 1,
FirstName = "Zia",
LastName = "Qammar"
});
session.Save(st);
}
trans.Commit();
}
}

- 174
- 12