代码改变世界

NHibernate Step By Step(5)-实体表现模式

2009-08-03 00:07  Clingingboy  阅读(653)  评论(0编辑  收藏  举报


1.默认持久化类,即一个配置文件对应一个实体类了

在JAVA世界中被称之为POJO(Plain Old Java Object).到了.net,就变成POCO(Plain Old Class Object)了,Class是我自己猜的

我们可以通过配置默认的配置文件default_entity_mode节点来修改,EntityMode 枚举定义了三种方式.

public enum EntityMode
{
    Poco,
    Map,
    Xml
}

2.动态模型

意图是创建实体映射文件,但不创建实体类(不是有实体类,不创建映射文件,实际上我好想这样…),好处就是不用创建实体类,可带来一些灵活性

如下配置文件 class节点不再指定table而是entity-name,做法是以Map的key,value方式来实现

<class entity-name="ProductLine">
  <id name="Id" column="productId" type="System.Int32">
    <generator class="native"/>
  </id>
  <property name="Description" not-null="true" length="200" type="string"/>

  <bag name="Models" cascade="all" inverse="true">
    <key column="productId"/>
    <one-to-many class="Model"/>
  </bag>

</class>
<class entity-name="Model">
  <id name="Id" column="modelId" type="System.Int32">
    <generator class="native"/>
  </id>

  <property name="Name" not-null="true" length="25" type="string"/>
  <property name="Description" not-null="true" length="200" type="string"/>
  <many-to-one name="ProductLine" column="productId" not-null="true" class="ProductLine"/>

</class>

我们还是看代码吧

(1)首先当然是修改默认实体表现模式了
configuration.SetProperty(Environment.DefaultEntityMode, EntityModeHelper.ToString(EntityMode.Map));

(2)数据操作方法
IDictionary 接口来操作,保存的时候需要保存对象的名字需要与entity-name相同


IDictionary cars;
IList models;
using (ISession s = OpenSession())
{
    t = s.BeginTransaction();

    cars = new Hashtable();
    cars["Description"] = "Cars";

    IDictionary monaro = new Hashtable();
    monaro["ProductLine"] = cars;
    monaro["Name"] = "Monaro";
    monaro["Description"] = "Holden Monaro";

    IDictionary hsv = new Hashtable();
    hsv["ProductLine"] = cars;
    hsv["Name"] = "hsv";
    hsv["Description"] = "Holden hsv";

    models = new List<IDictionary> {monaro, hsv};

    cars["Models"] = models;

    s.Save("ProductLine", cars);
    t.Commit();
}


3.以XML做数据库

之前就有听说hibernate要支持这个功能,就不知不觉有了这个功能了,也不知道这个怎么样,我们常要读取xml文件,但又想以实体方式获取,这样就得一个个属性的赋值给实体,若实现与xml映射的话,就免了这个过程了,但我相信肯定会添加了其他的复杂度,这个功能暂时用到的不多,就不写了.

hibernate转到.net平台的移植度还是非常的高的,几乎一样了