NHibernate : Some Naked Thoughts

Please, Just Remember One Thing

Just for a few seconds forget everything you know about NHibernate.


Now, before I snap my fingers and everything comes flooding back, the only thing you need to know about NHibernate is that whenever you need to, you can easily circumvent it and do whatever is needed to get the job done (like use an IDbConnection and IDbCommand to execute a stored procedure).


I often hear people saying it, and often say it myself, but people just don’t seem to get it. You use NHibernate to save yourself from having to write a ton of code for 95% of your data access, and then, after profiling, optimize the critical 5% with whatever other approach you prefer. Its stupidly easy. You can access an IDbConnection directly from an NHibernate’s ISession, or subclass your NHibernateDataAccess class with an SqlServerDataAccess class and override those critical sections.

Instead of taking the above sane approach, I see people laboring through huge amounts of mundane code in order to keep control over that unique 5% (maybe a special report, or performance sensitive path). I see people concerned about performance, without understanding that for most of what an application does, the performance difference between method A, B and C are indistinguishable, whereas the maintenance and developer costs vary hugely.

Essentially I see people who are worried about not being able to tweak when necessary and people who simply don’t want to change.

To the first group I say that your fears are understood, but not to worry. You can always drop down to the assembly of data access (SQL, Sprocs, …).

Four Areas of Improvement

NHibernate makes my life easier and my code better, but it isn’t without problems. A lot of these have to do with the fact that it’s trying to solve a complex problem, of which numerous variations exist. As such, NHibernate’s biggest problem is that it’s hard to learn and harder still to master. There are some specific pain points I’d like to see addressed.

First, mapping needs to be simplified. It’s extremely intimidating to a newcomer and requires that you understand most of the fundamentals. This is already being addressed with FluentNhibernate and hopefully the project will continue to mature.

Secondly, collections and references can be particularly puzzling. From the names used (bags, maps and sets are all foreign to most .NET developers), to advanced features like caching, lazy loading and cascading. I’m not sure if this is something that can actually be improved, or if this battle needs to be fought via documentation.

Thirdly, neither HQL nor Criterias feel like the most natural querying languages. Hopefully development on Linq to NHibernate will continue to be a priority.

Finally, NHibernate is an abstraction that will leak. This shouldn’t be unexpected, but it would be nice to try and address some of the worst offenders. The leaks that continuously trip me up are related to management of ISessions. Lazy loading and session management is a black art – doubtlessly easy for masters, and frustrating for everyone else.

NHibernate and Microsoft

Microsoft has long been criticized for its attitude towards open source frameworks. The common approach appears to be to compete with established open source frameworks using inferior solutions. MSTest, MSBuild, Sandcastle, ASP.NET Ajax, ASP.NET MVC, Entity Framework, Unity, Logging Application Block, Velocity, Team Foundation SSC are all examples that come to mind.

It’d be nice if Microsoft took a different approach with NHibernate, by not only acknowledging its presence and using it in samples and demos, but also actively contributing to it. Remember, during NHibernate’s lifetime, Microsoft has invented three distinct data access strategies (DataSets, Linq to SQL and the Entity Framework). So much effort, so much relearning by developers, to end up with a poor replica of NHibernate years later.

A couple years ago, Google contributed Hibernate Shards to the Hibernate project (and I’d bet that they’ve been involved in Hibernate in other ways since then). Surely Microsoft can help fund the project in a manner that works with the NHibernate team (money or resources).

NHibernate and You

I do think it’s important for any developer to learn new things. Equally important is to learn them from different people. Its important that you learn Ruby or Python, not because you should use them, but because seeing MVC over ActiveRecord completely changes your perspective on how applications can be built. The more approaches that you know, the more likely you are to pick the right one for the job. If you only know one approach then you’ll always use that one – and you better hope like hell that the person selling you that approach knows what he or she is talking about.

As for NHibernate specifically, most developers should learn about O/R mappers. You should know the advantages and disadvantages and therefore know when a situations calls for it or not.

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

28 Responses to NHibernate : Some Naked Thoughts

  1. Fabio Maulo says:

    Btw, friends, NH is a working reality but I’m pretty sure that EF will be the standard in .NET

    Each time this matter rises what I say is always the same:
    2 dogs and 3 or 4 cats, working on his free time can’t do the same of a monster as Microsoft is.

  2. Andrew says:


    “Well it’s true the power and influence, but then if they match up the product and make it better, I don’t see a problem. If they don’t, I don’t think companies are stupid enough to adopt it. May be 5 years ago it was true, no longer now.”

    Companies are just as dumb now as there were 5 years ago. How many large companies roll their own database access code primarily because Microsoft doesn’t have an ORM? The number is staggering.

    Large companies that are Microsoft houses do what Microsoft says, pure and simple. Yes, I’m sure there are exceptions, but for every one you show me that don’t, I can show you 20 that do.

  3. José Filipe says:

    (4 days long for an answer, I really had forgot this thread, sorry)


    Agree with you that MS will release EF4 and the full set of patches next months, but I wouldn’t do the same. Supporting NHibernate and providing professional services around that would be a better option IMHO (considering my believes about a better programming enviroment, of course)..


    The “something they can put together as part of a bigger picture than an OSP..” is the kind of excuse that MS neither tries because it would go against their own speech about open patterns and interop. With MS strenght there is no doubt that once supporting a good project they could fight for a standard..

    Overall speaking, I really see a point in both sides here. I just think that agreeing with MS’ nowadays practices is giving up of open standards, OSS and a lot of other stuff that already are proven effective practices that, IMHO again, just add to the development community in general..

  4. Niall Connaughton says:

    Yes, NHibernate is relatively mature. But some people will always prefer a commercial product because the people selling it are trying to make money from it, so they are motivated to continue improving it. For some people, future advancement is as important as the current feature set. So many of the open source projects die a quiet death when the handful of developers working on them get married, get busy at work or just plain get bored/motivated by something different. Big companies need some confidence in the future.

    And before you rah rah rah on about how NHibernate is a growing, living thing, where is the full LINQ support for NHibernate? Last I heard, it was “coming soon”. LINQ is hardly young now.

    As for the point that it’s all so unfair that MS has sway with big companies, that’s plain wrong as well. The finance industry has an inherent distrust of anything with a Microsoft stamp on it. They’ll use C# for front ends – Winforms or ASP.Net, but that’s the bulk of what they trust it for. Oracle heavily outweighs SQL Server despite the toolset for SQL Server being much richer, and Java is by far the dominant server technology. Suggesting C# for the server is likely to get you laughed at, and bringing up SQL Server worse. There are some banks that use more MS technologies, but for most, the anti-Microsoft sentiment is very strong. As for source control, you can forget TFS. It’s SVN (if you’re lucky), otherwise it’s just plain CVS.

    Speaking of source control, what open source source control systems out there have the feature set that TFS does? How is TFS reinventing the wheel. Say it sucks, or that it’s too expensive, but it does things that many other source control providers don’t bother implementing. Source control should be more than a text diffing engine used from windows explorer and plugged into a half arsed port of a better open source Java continuous integration system.

    Sure, a lot of what MS puts out is half baked. But maybe they want to put their efforts into something they can put together as part of a bigger picture than an open source project that has no guarantee it will keep up with the rest of the MS platform.

  5. TD says:

    Documentation will always be a problem for such a big, complex, and open source product as NHibernate. It’s simply not efficient hunt around the Internet for bits of of information and try to piece them together.

  6. Parag Mehta says:


    That is true. We are in business where we have to take decisions based on whether Enterprise Support is available or not. We can’t adopt a “mature” technology and then if we find a bug, we have to request community to fix without any timeline on it. Yes, we need to *have* solid support before we adopt anything.

    Rest of your stuff like nHibernate was based on defacto standard in Enterprise data access etc, is based on your hunch not statistics. We worked on several Enterprise class apps and didn’t use nHibernate up untill now. Though I am evaluating, I would prefer something from Microsoft rather then OpenSource. Again it’s personal decision mixed with business sentiments.

    Just for Info : We have been using LLBLGen Pro up untill now with great success. We are evaluating EF v4 and nHibernate for new projects, but we are happily maintaining the current ones.

  7. Matt says:


    NHibernate is a rediculesly stable and mature product. It was based on the defacto standard in enterprise data access, and has been extended to work better in .net idioms. Entity framework is the new kid on the block, they haven’t even really settled on the direction they are taking things yet.

    If you choose stable, mature, and proven technologies, nhibernate should be at the the top of your list. You say you choose it because it is backed by microsoft. So? Like karl said, so were datasets and l2s. Considering how long it has been around, and how much microsoft likes rewriting things, chances are it will outlive EF as well.

    The only reason I could imagine using EF is if you are in a shop where these descisions are not made for technological reasons. Because if you are coming at this from a purely technology point of view, there is no conceivable reason not to use NH for enterprise data access.

  8. Fabio Maulo says:

    @Joe Chung
    What it is needed is the interface and not the concrete class. We can’t use HashSet because the concrete class can’t be proxy (for some reason Ms has realized it in .NET4)… late is better than never

  9. Fabio Maulo says:

    A renew of MSDN premium would be enough for me.

  10. Parag Mehta says:

    @José Filipe
    Nice point. However realistically, I don’t think it will happen. Microsoft will have EF v4. I don’t see a point to this discussion. If I were Microsoft, running a company I would do the same and have something on my own that I have full rights on, rather then adopting Red Hat’s stuffs.

  11. José Filipe says:

    Great post Karl!

    I really understand people saying that competition must be encouraged, but my perception is that MS stuff is always one step ahead because “drag and drop” developers are undoubtly the majority – it’s fare considering that becoming a “real” developer takes time, but we have to be truth and agree that drap-and-drop is the default behavior in .NET community. And it’s sad.

    I really agree with Mihailo when he talks about the influence of MS over big companies. I’m really happy that we’ve some Java buddies here that support some decisions, because I’d be really frustated if we had dropped NH some years ago to try Linq2SQL, EF1, EF2 and so, MS spent heaps of money clearly trying to create a framework AS GOOD AS NHibernate, but in a visual way.. there are more options because that? Oh yes, there are, but wouldn’t be better if part of this money was invested in NH, giving it a “drag-and-drop” shell to give MS target developers the easiness they need to do their job?

    The speech around “C# isn’t Java” really doesn’t convince me. OO is OO, patterns are patterns, if you have a good solution in one side the logical way is to have a port in the other. The feeling is that our (.NET devs) pride will be hurt if we say “Ok, NH and log4net were and still are better then MS alternative even after huge amounts of money spent”. Come on, let’s think in practices and architecture decoupled from the language, both sides will only win..

    All that, ok course, IMHO..

  12. Parag Mehta says:


    Well it’s true the power and influence, but then if they match up the product and make it better, I don’t see a problem. If they don’t, I don’t think companies are stupid enough to adopt it. May be 5 years ago it was true, no longer now.

    I used jQuery much before MS adopted it. Sure the idea of being able to call MS Support for jQuery issues does make it lucrative for companies.

    For same reason, I will choose MS products if they are stable as oppose to Open source stuff. Speaking off Open Source, EF is also free, they are making money only on tools. I don’t see any difference with nHibernate, people are and will make money with Tools on it as well.

    I don’t think nHibernate is the answer to every data needs and personally I don’t like the notion of C# being second grade to Java, follow what they do.

    So I am in MS Support camp for innovating and giving us more options.

    Then again it’s my personal view…

  13. Mihailo says:


    I disagree with your disagreeing :)

    First of all you’re not addressing what Karl said there but talking about “free” market situation instead.

    Once jQuery became backed up by MS all of a sudden we could use it in our projects, before that it was frowned upon. EF comes to market all of a sudden we are talking about it as the one and only ORM.

    You are underestimating power and influence of MS in big(ish) companies. It is rarely developers who are doing decisions.

  14. Parag Mehta says:

    Your quote :
    “I agree with you, provided that the competition is fair. Specifically, you cannot leverage your dominance in one area to gain dominance in another. This is exactly what Microsoft did with IE and Windows, and what I feel is fair to accuse them of doing with countless OSS framework libraries and VS.NET+MSDN.”

    I don’t agree with this. Even though they do integrate it, the end choice is in hands of the developer. If they choose other Framework then nHibernate, you can’t call them wrong. So as long as choice is in hands of developers, it’s fair and democratic. Suppose EF gets more popular and nHibernate looses marketshare to it, then so be it. It’s choice made by so many developers! You can’t call them stupid for not selecting product which you back.

    Remember a saying, “If you see stupids everwhere, may be the problem is you!”.

  15. Ryan Rauh says:

    Execellent post Karl! I was unaware that I could get an IDbConnection from ISession and spent the afternoon, refactoring my 5% to use it instead of SqlCommand.

    I felt quite clumsy adding adding parameters to IDbCommand but that is obviously not NHibernates fault. Example of why NHib rock:

    You don’t have to write stuff like this

    using (UnitOfWork.Start())
    using (var cmd = UnitOfWork.CurrentSession.Connection.CreateCommand())
    cmd.CommandText = “usp_Foreign_DataLoad_I”;
    cmd.CommandType = CommandType.StoredProcedure;

    var parameter = cmd.CreateParameter();
    parameter.DbType = DbType.DateTime;
    parameter.ParameterName = “AsOfDate”;
    parameter.Value = asOfDate;


    parameter = cmd.CreateParameter();
    parameter.DbType = DbType.Int32;
    parameter.ParameterName = “Format”;
    parameter.Value = format;



  16. This is exactly the kind of reasoned, balanced post that the .NET Open Source community needs to make its case to developers who have only been exposed to the gospel according to Redmond. Excellent discussion of the limitations of NHibernate while still making a good case for its use. Great work, Karl!

  17. karl says:

    I agree with you, provided that the competition is fair. Specifically, you cannot leverage your dominance in one area to gain dominance in another. This is exactly what Microsoft did with IE and Windows, and what I feel is fair to accuse them of doing with countless OSS framework libraries and VS.NET+MSDN.

    They don’t necessarily out-innovate, they merely out-market and integrate.

  18. I agree with every word and punctuation in what you just wrote, Karl!

    And I am a firm believer that Fluent NHibernate with the AutoPersistenceModel lowers the bar of entry so much that I would recommend people use NHibernate even for the smallest tasks that require RDBMS persistence – it actually succeeds in making NHibernate feel lean, like lesser frameworks like e.g. Linq2SQL or SubSonic.

    I agree with Rob though – competition is good! But I still felt offended, and my feelings were a little bit hurt when Microsoft started that EF thing – probably because I fear that so many people will never learn NHibernate now, because their managers will force them to use the EF.

  19. Unity is a very nice DI Container library; I have few issues with it. Not that there’s anything wrong with StructureMap.

  20. Rob says:

    Let me play Devil’s advocate for a bit :-) Competition is actually a Good Thing. Instead of everyone herding like sheep to the same product(s) (Wikipedia “groupthink”), let developers of said products compete against each other. When MS creates something inferior to OSS, it should deservedly get spanked, and the same goes for OSS. We often talk about in sparkly terms about OSS, but what we’re really looking at are the few handful of successful projects that rise above the mire of flotsam in the vast software graveyard of failed OSS projects. After all, most good OSS contributions in the ALT.NET space are a direct response (competition) to shoddy offerings by MS. But if everyone “settled” for a single technology, there would be less incentive to find the next best thing. Diversification works wonders in the natural world, and I think it’s a good thing with respect to software as well. In that sense, we the users vote for the survival of the best by simply using what we feel is best. NH has survived while at least 3 MS offerings have been relegated to the Darwinian trash bin of software evolution. Why do we need a less democratic, more tyrannical system of bowing to one single product? Simply to justify our feeling of OSS superiority, or because we feel the need to rant?

  21. Matt says:

    3. Microsoft should certainly stop trying to reinvent the wheel – and it should certainly stop trying to compete with circular wheels by introducing triangular wheels.

    This is true… but I also think that Java developers should stop trying to turn .NET into Java. It’s not Java. Whether it’s better or worse you can argue all you want, but it’s not Java.

    I have learned to stay away from anything that came out of the Java world. NHibernate is just a hack from someone trying to write Java in .NET.

    I see your circular wheel and raise you a hover-craft. :)

  22. Ezequiel says:

    NHibernate and Me.
    Great post, I felt identified with it.
    Actually I’m working in a project that involves taking out Nhibernate and spring of an asp.net solution.
    I’m replacing it with “POCO” classes (new microsoft term) and “IDbConnection and IDbCommand” like you said. Two projects, one DataAccess and One Bussiness layer, to solve performance problems… so for me, not always save coding time is the solution… YO HAVE TO WORK!!! there is not magical solutions.
    I’m very glad with microsoft is doing in .NET 4.0 with EF… Im using it as or mapper in personal proyects… and I think it will be the best of them.

    Sorry for my english…
    Ezequiel from Argentina

  23. Tigraine says:

    I completely agree Karl.
    And mostly I think Microsoft has to get their legal act together in regards to OSS and start to be able to support projects like NH the way they do with jQuery and MVC.

    greetings Daniel

  24. Oh Wow! A positive blog post. Rock on Karl!



  25. Parag Mehta says:

    While nHibernate is good, it’s not for drag/drop developers. If you know what I mean!

    Microsoft wants to take the lessons from nHibernate and make it friendlier for drag/drop developers who don’t think too much about architecture.

    Looking at Entity Framework 4(yes! not 1.1 or 2), I think they have finally succeeded in creating a good tool. Once Entity Framework is mature and stable, I would take that approach for my clients rather then going the nHibernate Route. Reason : Simple : backed by Microsoft.

  26. Joe Chung says:

    Re: .NET missing a set class, no, it isn’t: HashSet
    http://msdn.microsoft.com/en-us/library/bb359438.aspx. In your defense, this was introduced in 3.5.

    Microsoft has a long history of reinventing the data access wheel that goes back over 15 years, long before NHibernate was around: ODBC, DAO, RDO, OLE DB, ADO, ADO.NET, System.Data.DataSet, LINQ to SQL, LINQ to Entities.

    Old habits die hard.

  27. Justice says:

    1. .NET is missing certain key collection classes, such as Set. Set is what we actually want when dealing with entities, so while it is unfortunate that .NET lacks the concept, Java provides it and NHibernate distributes a public domain implementation of it.

    2. Control over fetch strategy should in general be a part of ISession and IQueryable. NHibernate is a leaky abstraction only if you neglect to include certain key elements in the abstraction such as fetch strategy and cache strategy.

    3. Microsoft should certainly stop trying to reinvent the wheel – and it should certainly stop trying to compete with circular wheels by introducing triangular wheels.

  28. Ben Hyrman says:

    Part of it is that the semantic language for NH just doesn’t translate well to a casual approach.

    The collections have always been a bit puzzling to me. You have bag if you want a generic IList, set seems to be the next most common and it brings in yet another library to learn (no fault of NH, it’s not like the framework has had a good set collection)… but then you have things that aren’t what you think they are, like List.

    And then there’s the fact that you set inverse on the parent if it’s controlling the relationship to the child.

    And the fact that things went lazy by default (if a beginner doesn’t understand that they’ll wonder why they’re getting this weird error around no virtual found for their property)

    Don’t get me wrong, though, I love NH. I’ve been using it since pre-1.0. The first time I used it in prod for a real client was 1.01 (I think). It’s rarely not been my ORM of choice. But, like you said, there’s no easy mode for it. It needs to accommodate someone who barely knows how to map along with someone trying to do some advanced stuff with idbags and joined subclasses….