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.
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.