Some basic concepts about one strategy to manage the NHibernate session
This is just a strategy!
Frequently,
we are asked how we should manage the session of NHibernate (referred
to as "session"). When should we open the session? When should we close
the session? How many sessions should we have open?.
I
will tell what I often do to manage the sessions. Other strategies are
possible for Other targets, These strategies will be subject of other
wikis.
Introduction
Let’s review some of its funcionalities before asking how we should manage the session:
1.
The session manages the persistence of our entities then the session
has information about the state of the objects at certain times (when
the objects were loaded)
2. The session has a cache, it
allows a single instance of each object that we load within it. When we
try to get an object which has already been loaded, the session returns
us a reference to the same instance of the class.
3. The lazy loading will use the session to get the objects only when they are requested.
Then...
If we
accept
the introduction is true then we may say:
A. Each object should be loaded and saved in the same session (reason 1).
B. The related objects should be loaded in the same session (reason 1 and 2).
C.
the objects with lazy loading should have the same session (opened) at
the time to load the lazy information (reason 2 and 3) unless we use an
eager fetching strategy. If we disregard it then we can have an
Exception of type LazyLoadingException with the message "no session" or
"session was closed" because we just did it, we closed the session
ahead of time.
D. When an object is modified, it is
modified again on the session because it is the same! (reason 2) the
changes aren't visible for other sessions until we do a Flush and
Commit of the transaction. Only after that, the changes are visible to
other sessions. This behavior is the key to know how many sessions are
necessary.
E. The session should be closed when we don't need the same instance of it (reason 1 and 2, considering A, B and C)