Monday, April 14, 2008

Mapping a view with Nhibernate

Something we've come up against in the last week is a need to map a view in Nhibernate. We have a reasonably complex data model with a hierarchical structure involving about four different tables that we wanted to represent as a single mapped entity in our object model. The obvious approach was to define the appropriate view and map that.

No joined tables in Nhibernate:

There seems to be some confusion on the web with a lot of people complaining that Nhibernate doesn't yet support the joined tables syntax that is available in Hibernate 3.0. While this is true, it doesn't prevent you from working with a database view as long as you don't need to update the underlying tables via Nhibernate.


The solution:

Map the view just as you would map any other table in your data model with the standard syntax:


<class name="MyEntity" table="MyView"/>

The only other change you need to make is in your property mapping. Add the update and insert attributes to ensure Nhibernate doesn't try and generate insert and update statements for your view.


<property name="MyProperty" type="String" column name="MyColumn" length="300" sql-type="varchar" not-null="true"update="false" insert="false"/>


That is probably obvious to most people, but there seemed to be enough confusion when I was searching about it that it seems worth stating it again here.

Labels: ,

4 Comments:

Anonymous Anonymous said...

Thanks for posting this. Some of us are still googling the basics to get into this Nhib thing.

I'm having a slight problem with the xml file, it seems to be wanting an id, getting the error:

The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'property' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, jcs-cache, cache, id, composite-id'

So on to the next google! I think step one is out of the way though.

9:34 am  
Blogger James Fitzsimons said...

Glad I could be of some help. If you want to post your mapping file on here I might be able to help you find your problem.

Cheers!

10:34 am  
Anonymous Anonymous said...

Hi Again,

I sorted the problem, I basically left out the id column, assuming that this needed to be unique, it doesn't. So I put the Id column back in and hey presto, working.

Is it me or is MVC and Nhib like object orientated classic asp, with all the db objects being available through intellsense..!?

I'm showing my age now.

Thanks again.

12:36 pm  
Blogger Flavio Souza said...

Thanks a lot! This post saved my day.

3:19 pm  

Post a Comment

<< Home