C军

不玩博客了!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一、组件简介

  组件(Component)可以理解为被一个对象所包含的对象而持久化,而并非一个实体。简单说来,假如数据库有FirstName,LastName这两个字段,我们在C#中可以将这两个字段提取出来作为一个Name对象使用。

  示例,首先建一张表,并添加数据如下:

  

  Person.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Model.PersonModel, Model" table="Person2">
    <id name="Id" column="Id" type="Int32">
      <generator  class="native"/>
    </id>
    <component name="Name" class="Model.NameModel,Model">
      <property name="FirstName" column="FirstName" type="String"/>
      <property name="LastName" column="LastName" type="String"/>
      <property name="FullName" formula="FirstName + LastName" type="String"/>
    </component>
    <property name="Age" column="Age" type="Int32"/>
  </class>
</hibernate-mapping>

  Model:

namespace Model
{
    public class PersonModel
    {
        public virtual int Id { get; set; }
        public virtual NameModel Name { get; set; }
        public virtual int Age { get; set; }
    }

    public class NameModel
    {
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual string FullName { get; set; }
    }
}

  Program.cs

        static void Main(string[] args)
        {
            PersonDao dao = new PersonDao();
            PersonModel p = dao.GetPerson(1);
            Console.WriteLine(p.Name.FullName);

            Console.ReadKey();
        }

  输出结果如下:

  

   1、每当重新加载一个包含组件的对象,如果组件的所有字段为空,那么NHibernate将假定整个组件为空。

   2、组件的属性可以是NHibernate类型(包括集合、多对一关联以及其它组件)。嵌套组件不应该作为特殊的应用被考虑。

   <parent>指定组件所属对象:

  我们修改Person.hbm.xml映射文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Model.PersonModel, Model" table="Person2">
    <id name="Id" column="Id" type="Int32">
      <generator  class="native"/>
    </id>
    <component name="Name" class="Model.NameModel,Model">
      <parent name="NamedPerson"/>      <!-- 引用所属Person对象 -->
      <property name="FirstName" column="FirstName" type="String"/>
      <property name="LastName" column="LastName" type="String"/>
      <property name="FullName" formula="FirstName + LastName" type="String"/>
    </component>
    <property name="Age" column="Age" type="Int32"/>
  </class>
</hibernate-mapping>

  Name类修改如下:

    public class NameModel
    {
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual string FullName { get; set; }
        public virtual PersonModel NamedPerson { get; set; }
    }

  这样,我们就能够转来转去:

  Console.WriteLine(p.Name.NamedPerson.Id);

  由人获得姓名对象,从姓名对象又能够找到人。

  感觉文章至此,对组件的了解还是不够,但是又实在没有办法到哪里去找到好的资料。暂时搁置。

  

 

 

 

 

posted on 2013-03-04 13:35  逆心  阅读(671)  评论(0编辑  收藏  举报