Wednesday, December 24, 2008

ORMs can do things quickly? Stateless activity with nHibernate 2.0

nHibernate does a great job of handling changes through the use of its session architecture. One difficult thing to do is break the mental lock you have on the word "session," especially if you've done any ASP(.NET),JSP type work. Session is more conceptual in this world. A session in Hibernate only lives long enough to service a call between your consumer and the store. That might be just enough to hydrate your objects, or long enough manage changes in your CLR objects, then persist those changes to the store.

So, what happens if you're just doing an insert? I don't really care about what's the in the database now, I just want to persist a new row there. There is a significant amount of overhead when building up a session, and if you're building something along the lines of a high-speed keying app, that's an issue (ORM detractors will being saying "shouldn't have picked an ORM" at this point.). One of the reasons you pick an ORM is that it manages a lot of changes, but that does require the use of caching and all the overhead that comes with that.

I've scanned dozens of blogs and couldn't find a good answer to this (yet). Then, the IStatelessSession.

The IStatelessSession doesn't do all of that work, therefore, much less overhead in the scenario where you want to do quick operations. Code might look a lot like this (once you have a concrete session factory established):

NHibernatePerson person = new NhibernatePerson();
person.Name = "Me";


using (IStatelessSession session =
  sessionManager.OpenStatelessSession())
using (ITransaction scopedTransaction =
  statelessSession.BeginTransaction())
{
    session.Insert(person);

    scopedTransaction.Commit();
}


P.S. Moments after posting this, I mentioned what I was looking for to someone online and was Im'd this blog link. Dangit. With metrics and everything! Well played, Mr. Brion. Well played.

BTW, in retribution, i stole your double using statement.

No comments: