The Inquisitive Coder – Davy Brion's Blog

Trying to walk that thin line between intelligence and ignorance

NHibernate Mapping Examples

Posted by Davy Brion on July 15th, 2007

When you’re starting out with NHibernate, it’s sometimes hard to find good examples. Most examples online are too simple, or are incomplete (just the mappings, but no code for instance). It’s always easier if you have some examples that are large enough, but still small enough to be easy to grasp. So i created mappings and classes for the Northwind tables. I figured this could be useful reference material for anyone new to NHibernate so i’m making the whole thing available for everyone. You’ll find examples of one-to-many, many-to-one and many-to-many associations in there. I used a couple of different cascade options for the associations, depending on the constraints on the tables. I’ve also included about 60 unit tests to verify the mappings are working correctly. These tests should also give you a good idea about how NHibernate deals with certain mappings and options.

I did modify the Northwind database here and there… the zip file contains all the sql create scripts. This is what my version looks like:

Northwind Table Diagram

And the class diagram looks like this:

Northwind Class Diagram

I do want to make it clear that this is just an example. I’m not saying that this how you should map your objects and their associations to tables and their relationships. I pretty much provided every possible association in this example, whereas on a real project i’d only create the associations that i actaully need to implement the required functionality. But for the purpose of this example, i thought it would be a good idea to provide as much as possible.

You can download it here

34 Responses to “NHibernate Mapping Examples”

  1. Julian Says:

    Really nice, I just took a look through the mappings in the solution. I just wondered if you could have supplied some examples of mappings using lists and maps as well. One can hardly ever find examples using these types of mappings, while bags and set are often demonstrated.

    Keep up the good work,
    Julian.

  2. Davy Brion Says:

    Good idea, i’ll try to put a new version of this online in a few days with some examples of lists and maps as well.

    There are a lot of other possible mappings that i haven’t explored yet, but if there are any other suggestions, i’ll gladly try to implement them.

  3. Tobin Harris Says:

    That’s a cool diagram :-)

  4. Jean Says:

    Great job.

    The only thing I would like to see is some comments in your code as I am new to ORM tools and C#.

    Just a suggestion though!

    Cheers

  5. Anonymous Says:

    Thanks for the example diagrams and code. Small enough yet very useful as an sample.

    One suggestion – you might want to add a copy of nunit.framework to the Lib folder to make the solution more self-contained. ;)

  6. Anonymous Says:

    Question – any particular reason you chose to let NHibernate use direct field access? Is there a performance advantage by doing so? Thanks.

  7. Davy Brion Says:

    thx for pointing out the nunit assembly issue… i’ve updated the zip file so it should be fixed now.

    As for the direct field access… that’s just a habit to be honest. I prefer to let NHibernate use the fields directly so i’m free to put whatever code i want in my setters without having to worry about it being executed when NHibernate is initializing an object. Granted, in these examples it’s unnecessary. As for performance, i haven’t benchmarked it but the direct field access should actually be a little bit slower than using properties.

  8. wayde Says:

    Great set of example mappings.

    Do you write up your mapping and class files by hand or use some type of code generation? Personally, I think it would be nice to at minimum be able to generate the mapping files given one or more tables/views in a database from which to work with. Basic stubbing out of a class file based on each mapping file would also be nice to start out with.

    If you have any suggestions, I’d be interested to know. Thanks again for your post.

    - wg

  9. Davy Brion Says:

    I did those manually, but at work we do have a custom code generator which will generate the mapping files and the classes based on the database metadata. If you go that route, i would suggest making it possible to differentiate between generating the files initially, and being able to regenerate them constantly. In some cases, you will want to do something different than what was generated by default, so you should be able to modify the generated files without being worried that they will be overwritten the next time you re-generate.

  10. Arvind Says:

    Davy,
    Looks cool! What is the custom code generator tool you use at work? I am looking for some tool to generate mapping files and the business entities.

    Thanks

  11. Davy Brion Says:

    Well i wrote the custom code generator for the client so unfortunately i can’t share it. Otherwise i would’ve put it online already :) . You can also try the templates at http://www.mygenerationsoftware.com allthough i haven’t used MyGeneration yet so i don’t know if it’s any good. But it’s free so it won’t hurt to give it a shot.

  12. Harsimrat Thukral Says:

    I have two tables something like this :
    Table : Account
    AccountID
    UserName
    Password

    Table : Address
    AddressID
    AccountID
    Line1
    Line2
    State

    My NHibernate mapping file looks like this :
    For Table Account

    For Table : Address

    My Problem is it does entry in the Account table perfectly, but when it comes to do entry in Address Table it says AccountID can’t be null, I’m wondering shouldn’t it pick it up from the Account table as I’m passing in that object.

    Is there something in the code need to be fixed ?

  13. Davy Brion Says:

    your mapping files didn’t make it through apparantly so i can’t reallly say much about this…

  14. hamlet Says:

    When I test this solution, I get exeption: “Could not compile the mapping document: Northwind.Domain.Mappings.ProductCategory.hbm.xml”. Why? What can I do?

  15. Davy Brion Says:

    did you make any changes to the file? because it works over here

  16. 2 Links Today (2008-01-16) Says:

    [...] NHibernate Mapping Examples « Davy Brion’s Blog [...]

  17. Ivan Says:

    Do you have some data for this new structure? or sql-script to transfer data from old northwind to northwind by u?

  18. Davy Brion Says:

    unfortunately i don’t…

  19. Scott Hanselman's Computer Zen - Deploying ASP.NET MVC on ASP.NET 2.0 Says:

    [...] or Entity Framework or anything. You’ll need to use something else. In my example code I’m using Davy Brion’s NHibernate Northwind Sample as it’s a .NET 2.0 compiled solution and it’ll be acting as my [...]

  20. Scott Hanselman's Computer Zen - Learn How to use NHibernate with the Summer of NHibernate Screencast Series Says:

    [...] I used NHibernate as my Data Layer recently when I got ASP.NET MVC running under .NET 2.0 using NHibernate examples from Davy Brion (who has an NHibernate Category on his [...]

  21. NHibernate Mapping Examples - NHibernate blog - NH Forge Says:

    [...] Note: this post was originally posted on July 15, 2007 [...]

  22. Kalyan Says:

    Very nice work, very helpful.

  23. jburrow Says:

    Firstly, Greate post. Very useful.

    I have a question i can google the answer! So i am hoping you may know.

    I have a classic many-to-many situation in my database.

    Table1(id|…) === Table3([id|table1.id|table2.id|sortOrder])=== Table2(id|…)

    I have mapped this to my classes and this is working fine with each entity containing a collection of the other one.

    however i have a column on my join table3 (sort order). And i dont know how to get hibernate to map this onto either entity.

    Suggestion would be welcome. I hope i have explained the situation clearly enough.

  24. Davy Brion Says:

    I don’t think you can do that… A true many-to-many only has two keys… once another column is added, it’s considered an own entity in its own right. In this case it might seem a bit drastic because of the column only contains a SortOrder, but i’m affraid you won’t be able to use a many-to-many association for that

    I can be wrong though :)

  25. Jamie Says:

    JBurrow, probably too late of an answer, but I had to tackle the same thing (a many-to-many with an additional value). You just need to define the association table in one of the containing classes. For your example:

  26. Jamie Says:

    Well.. that didn’t work… (no xml posting… duhh). (why is there no preview?)
    Without the xml, it’s:

    class name=”Table1Class” table=”Table1″
    set name=”Table3s” cascade=”save-update” table=”Table3″
    key column=”Table1ID”
    composite-element class=”Table3Class”
    property name=”SortOrder”
    many-to-one name=”Table2Class” column=”Table2ID”
    /composite-element
    /set
    /class

  27. Albert Araalie Says:

    I’ve used the samples successfully! Thanks alot! How would I map a view that queries the Employees’ table, through to the Products’ table? An initial complaint from nhibernate is that it cannot find an id field.

  28. The Inquisitive Coder - Davy Brion’s Blog » Blog Archive » What Would You Like To See In My Upcoming NHibernate Examples? Says:

    [...] original version of my NHibernate Mapping Examples was pretty popular, but they were based on NHibernate 1.2 and only showed some of the basics. I [...]

  29. RichB Says:

    Beautiful.
    My only complaint is that it could have done with some complex HQL examples.

    “from Employees e where e.Orders.OrderLines.Discount > 5″

    …and I know that won’t compile, because that demonstrates what I’m stuck trying to do. I was hoping your fantastic Northwind solution which give me the answer.

  30. Ibrahim Says:

    Hi..

    I am new to NHIbernate.
    Can anybody tellme how to do mapping / solve the current situation..

    Product Table Category Table

    productid categoryId
    productname category
    productdescription
    category{string type}

    Current Window: Product.Xaml [iam binding product entity to this form/window]

    and my requirement is while accessing product entity from product table i need to access all categories from category table.So that it will be binded to a dropdownlist. is it possible? or i need to bind categories programmatically after loaded product entity ?

  31. Salman Says:

    Great example!

    Curious, did you use any tools for generating your mappings?

  32. Davy Brion Says:

    @Salman

    nope, i don’t really believe in them :)

  33. Salman Says:

    Davy,

    In your example, you have a many-to-many relationship for territories and employees.
    You used a Set in the Territory mapping file, and a bag in the employee mapping file.

    Don’t you need to set one of them with the inverse=true attribute? To tell nhibernate which entity collection to use when their is a change?

  34. Salman Says:

    ah ok, you only have the Territory entity that is able to add/remove employees, so its not bidirectional in that manner :)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>