NHibernate - How to Iterate Persistent Entities Attached to a Session? - nhibernate

I have a need to inspect the set of attached entities that would be persisted if I called Flush() on a given session. (I'm writing code that accesses a Session as part of a generic pipeline before saving and it can be used in any number of contexts.)
I find myself wishing that there were a method like
mySession.GetPersistentEntities()
so I could inspect them and perform some preprocessing.
Anyone know of a way to do this?
Thanks,
Jeff

No, NHibernate's ISession does not expose anything like that. You can either:
Track these instances yourself (not recommended)
Use standard NHibernate mechanisms:
Event listeners (e.g. IFlushEventListener, ISaveOrUpdateEventListener)
Interceptors (IInterceptor.OnFlushDirty(), OnSave())

You could "hack" a little bit into the session context:
ISession session;
var sessionContext = session.GetSessionImplementation().PersistenceContext;
foreach(var entity in sessionContext.EntitiesByKey.Values)
{
// do anything with the entity
}
However, in your case I would use flush event listeners or an interceptor.

Related

Force NHibernate to get entity that is already in persisted state / 1st level cache

I have a service object that is responsible for some business logic validation. What it does, before issing Update to repository, is checking whether entity that it works on complies to some business rules.
One of that rules that is must check is if Status property of the entity didn't change when compared to entity that is in database. Because I use repositories that share the same ISession, when I try to get entity from database, in order to get an object for comparsion:
if (fromDbEntity.Status != entity.Status) throw new Exception("Cannot change status...");
I'll always get fromDbEntity that is in 1st level cache - so I work on the same object.
Is there a way to force NHibernate/Repository to get entity from database even though it's already in the scope of the session?
Evict entity from session before loading fromDbEntity
session.Evict(entity);
You can check the official documentation for more details: Managing the caches
The con about this is that you will need to manually call SaveOrUpdate for entity since now the object is out of the session.
You could, as Claudio suggests, evict the entity from the session, then load your fromDbEntity, do the comparison and then Merge the entity again with the session.
Other thing you might do is loading the fromDbEntity using the stateless session instead.
But is this really necessary? Couldn't you just make your Status property read-only? NHibernate is perfectly capable of using fields for accessing data. Or you could make your property setter protected:
public virtual Status Status { get; protected set; }
This way the user won't be able to change the property value, so there's no need to check whether current value is different from db one.
I had a similar issue, I solved it by clearing the session before any call that I want to go all the way to the data base.
session.Clear();
It's a little overkill but it works.
The way you sate your logic, it sounds like there's a potential bug. A much better solution would be to turn on dynamic-update, thus only updating changed values, then validate that no one has changed Status before saving.

Ninject / NHibernate Events + Observer Pattern

I am trying to implement an observer pattern using ninject and NHibernate.
I'd like to be able to inject observers that act as "triggers" when an object is persisted or deleted via NHibernate.
Key points-
I want the observer to be notified any time an object is persisted, including cascaded saves, which is why I am using NHibernate PostInsert/PostUpdate events.
I want to be able to inject the observers via Ninject (don't want the kernel anywhere in the nhibernate event handlers).
The observers are different depending on the type of the object being persisted, so I need a good way to know which observers should be called in the NHibernate events.
My code works great now for objects that are loaded via NHibernate using constructor injection. An observer class is injected into the domain model, which is carried through the nhibernate events and can be fired off no problem.
The problem: Our existing codebase uses default constructors for our domain objects versus a factory. Because of this, the observers will not be injected unless we switch to using a factory.
I know that switching everything to a factory will work, but I wanted to see if anyone has any better suggestions for accomplishing this. So, should I make a factory to instantiate new objects or something else?
It looks like you are making life complicated for yourself by trying to put Observer pattern on top of NHibernate's Event Handler pattern.
NHibernate already provides a way of having pluggable event listeners - why not just make use of that?
class FooPostInsertEventListener : IPostInsertEventListener
{
public void OnPostInsert(PostInsertEvent #event)
{
var entity = #event.Entity;
var entityType = entity.GetType();
if (entityType != typeof(Foo)) return;
ProcessFoo(entity);
}
}
If you are desperate to go through the Kernel, then you can even use the Kernel when configuring NHibernate. Something like this:
config.EventListeners.PostInsertEventListeners = Kernel.GetAll<IPostInsertEventListener>().ToArray();

nhibernate and sessions, please clarify

I am building a web application, and whenever I make a database call I need a session.
I understand creating a session object is very expensive.
I am following the repository pattern here: http://web.archive.org/web/20110503184234/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx
He uses something called a UnitOfWork to get the session.
For a web application, shouldn't I be storing the Session in Request.Items collection? So its only created once per request?
Do I really need UofW?
The session IS the unit of work - its basically used to store changes until you flush them to the db. Save a static session factory at startup, and use that to create one session per web request - Request.Items seems a valid place to put the session.
The repository pattern is a wrapper over the unit of work. The repository pattern differs from the UoW pattern in that repo.Save(obj) should save the obj to the db straight away, while the UoW waits for a flush.
My advice would be to skip the repository pattern and use the ISession directly (see http://ayende.com/Blog/archive/2009/04/17/repository-is-the-new-singleton.aspx)
In the case of NHibernate the key class is the SessionFactory, which SessionProvider is taking care of for you (if you implement it like that). Keep the SessionFactory alive, and it handles the sessions for you.
I've also seem people save the SessionFactory in their IoC.
Use this to manage your sessions:
HybridSessionBuilder
It manages and gives you access to a single session that's used across the entire application.

NHibernate sessions - what's the common way to handle sessions in windows applications?

I've just started using NHibernate, and I have some issues that I'm unsure how to solve correctly.
I started out creating a generic repository containing CUD and a couple of search methods. Each of these methods opens a separate session (and transaction if necessary) during the DB operation(s). The problem when doing this (as far as I can tell) is that I can't take advantage of lazy loading of related collections/objects.
As almost every entity relation has .Not.LazyLoad() in the fluent mapping, it results in the entire database being loaded when I request a list of all entities of a given type.
Correct me if I'm wrong, 'cause I'm still a complete newbie when it comes to NHibernate :)
What is most common to do to avoid this? Have one global static session that remains alive as long as the program runs, or what should I do?
Some of the repository code:
public T GetById(int id)
{
using (var session = NHibernateHelper.OpenSession())
{
return session.Get<T>(id);
}
}
Using the repository to get a Person
var person = m_PersonRepository.GetById(1); // works fine
var contactInfo = person.ContactInfo; // Throws exception with message:
// failed to lazily initialize a collection, no session or session was closed
Your question actually boils down to object caching and reuse. If you load a Foo object from one session, then can you keep hold of it and then at a later point in time lazy load its Bar property?
Each ISession instance is designed to represent a unit of work, and comes with a first level cache that will allow you to retrieve an object multiple times within that unit of work yet only have a single database hit. It is not thread-safe, and should definitely not be used as a static object in a WinForms application.
If you want to use an object when the session under which it was loaded has been disposed, then you need to associate it with a new session using Session.SaveOrUpdate(object) or Session.Update(object).
You can find all of this explained in chapter 10 of the Hibernate documentation.
If this seems inefficient, then look into second-level caching. This is provided at ISessionFactory level - your session factory can be static, and if you enable second-level caching this will effectively build an in-memory cache of much of your data. Second-level caching is only appropriate if there is no underlying service updating your data - if all database updates go via NHibernate, then it is safe.
Edit in light of code posted
Your session usage is at the wrong level - you are using it for a single database get, rather than a unit of work. In this case, your GetById method should take in a session which it uses, and the session instance should be managed at a higher level. Alternatively, your PersonRepository class should manage the session if you prefer, and you should instantiate and dispose an object of this type for each unit of work.
public T GetById(int id)
{
return m_session.Get<T>(id);
}
using (var repository = new PersonRepository())
{
var person = repository.GetById(1);
var contactInfo = person.ContactInfo;
} // make sure the repository Dispose method disposes the session.
The error message you are getting is because there is no longer a session to use to lazy load the collection - you've already disposed it.

Get list of changed fields in Entity from NHibernate Session

I want to track changes in my domain model. I know that NHibernate ISession is an inmplementation of UnitOfWork pattern, so it tracks this changes. Is there any way to pull out them, for example, before Commit() or Flush()?
Take a look at NHibernate's IInterceptor.
OnFlushDirty - will show you persisted properties on an updated object.
OnSave - will shows you persisted properties on a saved object.
You just need to create an interceptor class that implements this interface, and when you configure your NHibernate session, tell it to use that class.
Here is a fairly good article to help you get started
I think than Interceptors are a little bit obsolete. Š•rying to use NHibernate Events. I've subscribed on OnPreUpdate event. It's parameter has State and OldState properties, but OldState is allways null. Does anyone know this OldState works at all?