Chapter 1
9
Next, we create our mapping for the Product entity class. Visual Studio uses the
nhibernate-mapping.xsd schema to provide IntelliSense while completing this mapping.
As a general rule, all NHibernate mapping les end with a.hbm.xml extension, and have a
build action of Embedded Resource. NHibernate searches through the embedded resources
in your assembly, loading each one with this extension.
One of the most common mistakes in mapping is forgetting to set the build
action to Embedded Resource. This leads to the "No Persister for class"
MappingException.
Let's break down this XML mapping. Every XML mapping document contains a single
hibernate-mapping element. The xmlns attribute sets the XML namespace. Along
with the schema in our Schema folder, Visual Studio uses this to enable IntelliSense
inside NHibernate mappings.
The
assembly attribute tells NHibernate which assembly, by default, contains our types.
Similarly, the namespace attribute sets the default .NET namespace types in this mapping le.
Together, they allow us to use the simple name Product instead of the full assembly qualied
name of Eg.Core.Product, Eg.Core. Inside the hibernate-mapping element, we have
a class element. The name attribute tells NHibernate that this class element denes the
mapping for our entity class Product.
The
Id element denes the POID. The name attribute refers to the Id property of our
Product class. It is case-sensitive, just as in the C# language.
The
generator element denes how NHibernate will generate POIDs. In this case, we've told
NHibernate to use the guid.comb algorithm. Several other options exist.
The
property elements dene properties on our Product class. Each name attribute
matches the name of a property on our Product class. By default, NHibernate allows null
values. Adding not-null="true" tells NHibernate to disallow null values.
Avoid redundant mappings
In general, it's best to keep your mappings as short and concise as possible.
NHibernate intelligently scans your model and combines this knowledge
with the information provided in the mapping. In most cases, specifying
the types of properties in your mappings only creates redundancies that
must be maintained. The default table name matches the class name,
and each column name matches the corresponding property by default.
It's not necessary to specify this information again. Similarly, you should
avoid setting an attribute in your mapping when it matches an NHibernate
default. For example, adding not-null="false" to each of your
properties is redundant, and makes your mapping difcult to read.