Wednesday, January 13, 2010

NHibernate – Defining mappings (Part 4)


NHibernate can be configured to run in almost any .NET Application and development environment. To configure NHibenrate the first thing you must do is to create and ISessionFactory instance from the configuration.
Before working on the configuration file, we’ll define our domain entities used in the application. We’ll start by defining the customer entity. The customer entity is a simple POCO class and uses automatic properties.
public class Customer : BaseEntity<long>
{
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Address { get; set; }
}
where BaseEntity is the common entity class that every domain entity in our sample inherits from.
public class BaseEntity
{
    public virtual T Id { get; set; }
    public virtual DateTime CreatedDate { get; set; }
    public virtual DateTime ChangedDate { get; set; }
    public virtual byte[] Version { get; set; }
}
The next task is to define the mapping between this class and the corresponding table in the database. This mapping is defined in an xml document, Customer.hbm.xml
xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="BlogsPrajeesh.NHibernate.Domain"
                   namespace="BlogsPrajeesh.NHibernate.Domain">
  <class name="Customer" table="Customers">
    <id name="Id" column="CustomerIntId">
      <generator class="identity" />
    id>
   
   
    <version name="Version" generated="always" unsaved-value="null" type="BinaryBlob">
      <column name="Version" not-null="false" sql-type="timestamp"/>
    version>
    <property name="CreatedDate" type="DateTime" />
    <property name="ChangedDate" type="DateTime" />
    <property name="FirstName" not-null="true" />
    <property name="LastName" not-null="true" />
    <property name="Address" />   
  class>
hibernate-mapping>


Make sure that the mapping file’s build action is defined as ‘Embedded Resource’.  Next we’ll see how to configure NHibernate for the application.

No comments: